Avoiding watches in AngularJS for faster data bindings

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.

Add a Comment

Your email address will not be published. Required fields are marked *

*
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