Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can child scope $apply itself without applying parent

Is it possible for a child $scope (isolated or not) to do $scope.$apply without the parrent scope being applied?

There is some expensive computation going on (that is hard to cache) in the parent scope and I don't need angular to rerun the computation again.

for instance:

<div ng-controller="ParentController"> 
{{ expensiveFunction() }}
  <div directive>
    <h1 ng-click="applyChildScopeOnly()">Click {{ value }}</h1>
  </div>
  <div directive>
    <h1 ng-click="applyChildScopeOnly()">Click {{ value }}</h1>
  </div>
<button ng-click="applyChildrenScope()"/> <!-- apply to children scope only -->
</div>

The directive:

module.directive('directive', ['$document','$rootScope', function ($document,$rootScope) {

  return{
    restrict:'AE',
    scope:{},
    link:function($scope, element, attrs){
        $scope.applyChildScopeOnly = function(){
           $scope.$apply(); // don't apply changes to $parent scope
        };

    }
  }
}]);
like image 745
g00fy Avatar asked Apr 08 '13 15:04

g00fy


1 Answers

You can call $scope.$digest() instead of $scope.$apply() to re-evaluate watches in the current scope and all its children. Calling $scope.$digest() wont't evaluate any watches on any parent scopes.

As a side note, the $scope.$apply() calls the $rootScope.$digest() behind the scenes.

More info here: http://docs.angularjs.org/api/ng.$rootScope.Scope

like image 190
pkozlowski.opensource Avatar answered Sep 20 '22 16:09

pkozlowski.opensource