Home » Featured, Headline, Software Development

Avoiding watches in AngularJS for faster data bindings

26 April 2015 No Comment

AngularJS is a nice enterprise framework for UI development. It has all the cool features but as stated by AngularJS developers, it cripples itself if there are 2000 or more data bindings in the template. Well, 2000 maybe a smaller number if you are developing an enterprise application.

Have a look at the below angular code. For a 100 users, it will create 100 users x 12 watches = 1200 watches.

<ul>
    <li ng-repeat="user in users">
	<a ng-href="{{ user.profileUrl }}">{{ user.name }}</a>
        <a ng-href="{{ user.profileUrl }}"><img ng-src="{{ user.avatarUrl }}"></a>
        <div ng-class="{'formatted': user.description}" ng-bind="user.description"></div>
           <ul ng-if="user.subjects.length">
	      <li ng-repeat="subject in user.subjects">
		 <a href="/{{user.name}}/{{subject.code}}/{{subject.id}}">{{subject.name}}</a>
	     </li>
	  </ul>
    </li>
</ul>

Doing another iteration of users properties would easily exceed 2000 watches.

Below are some of the ways to solving the issue of 2000 watches.

Binding data only once
This technique creates a one time data binding and does not create any watchers. Some of the projects that use this technique are:
Angular-Once
BindOnce
Watch fighters

Using Timeout
This technique adds delays to scope variables, avoids creating watches and assumes the requests would be completed in a certain time interval.
This is not ideal for REST based watches.

$scope.$watch('data.response', function() {
   $scope.newresponse = $scope.data.response;
});

Instead of the above, we delay the response and put a loading flag for the UI.

$timeout(function() {
   $scope.loading = true;
   $scope.newresponse = $scope.data.response;
}, 4000);

Are there any other ways to solve this issue? If there are, please comment below.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image