Question

I'm following thinksters angular nfl fantasy tutorial here http://www.thinkster.io/angularjs/eHPCs7s87O/angularjs-tutorial-learn-to-rapidly-build-real-time-web-apps-with-firebase and they implement the ng-class active in this way...

<li data-ng-repeat="entry in navbarEntries" data-ng-show="auth" data-ng-class="{ active: entry.isActive }">


$scope.$on('$routeChangeSuccess', function() {
    $scope.navbarEntries.forEach(
      function(data) {
        data.isActive = ($location.path().indexOf(data.link) == 0);
      }
    )
  })

They have this explanation for the implementation below...

"Why, might you ask, wouldn't you just call a method from the view, which would assess if it should be active or not?

The reason is the $digest cycle re-evaluation. This cycle occurs very, very often, and every method call you use in your view to assess property will be re-invoked every single cycle, which will obviously degrade performance as the application scales."

I'm wondering what it would look like to "call a method from the view", what "to assess property" means, and would like a bit more of an explanation in what cases to use like this to avoid $digest cycle re-evaluation is appropriate in angular.

Was it helpful?

Solution

To call a method from the view would look something like this:

<li ng-class="{active: urlIsActive('/home/')}"><a href="#/home/">Home</a></li>

Then urlIsActive would be a function in the scope, like this:

$scope.urlIsActive = function(url) {
    return ($location.path().indexOf(url) == 0);
}

The problem with this approach is that the function urlIsActive would have to be re-evaluated on every scope digest cycle, wasting a lot of performance. The approach they suggest is using events to manipulate scope variables instead, which is cheaper in terms of performance.

Note that the suggested scope variable manipulation occurs when an event is fired. When rendering the page, finding out if a link should be active is just a simple variable lookup, rather than actually executing a function (which has a lot of overhead in itself).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top