Gal Ziv
Gal Ziv

Reputation: 7372

Angular child scope updated from ancestors but not updating ancestors

I want to know if there is a way to make a child scope changes (which initiate $apply) from causing a $rootScope.$digest (part of the $apply method). When doing this, I still want this scope to be update when another ancestor scope initiate $apply (which calls $rootScope.$digest()). And also when this scope calls $apply it will still update it's child scope.

For exmaple: Father --Son ----Grandson

Father, ng-click -> updates Father,Son,Grandson Son, ng-click -> update Son, Grandson Grandson, ng-click -> updates Father, Son, Grandson or even updates Son, Grandson

I managed to do that with a minor change in angular's source code (about 3 lines of code).

Since it won't be a part of angular's official versions (unless I'll do a pull request and will be merge) I was wondering if there is already a method to accomplish that.

Thanks in advance!

Upvotes: 2

Views: 156

Answers (1)

malix
malix

Reputation: 3572

This implementation inherits properly:

//app.js
var app = angular.module('app', []);

app.run(function($rootScope){
  $rootScope.info = {data: 1};
});

app.directive('page', function(){
  return {
    restrict: 'E',
    replace: true,
    transclude: true,
    scope: true,
    template: '<div class="page" >Component "{{name}}":<pre ng-click="update()">{{info | json }}</pre><div ng-transclude></div></div>',
    controller: function($scope) {
      this.name = function(){
        return $scope.name;    
      };
      this.data = function() {
        return $scope.info.data;  
      } 
      $scope.update = function() {
        $scope.info.data = $scope.info.data + 1  
      }
      $scope.info = {data: 0};
    },  
    link: function($scope, element, attrs) {
      var parent = element.parent().inheritedData('$pageController');
      console.log(element.parent(), parent); 
      $scope.name = attrs.name || '???';
      $scope.$watch(function(){
        return parent && parent.data();  
      },function(a,b){
        if(a !== void 0 && a !== b) {
          $scope.info.data = a;
        }
      })
    }
  }; 
});

//index.html
<body ng-app="app">
  <h1>Test</h1>
  <page name='GrandFather'>
    <page name='Father'>
      <page name='Son'>
      </page>
    </page>
  </page>
</body>

[UPDATED] http://plnkr.co/edit/ywZw3J7pL1GQPZiRnkol?p=preview

Upvotes: 1

Related Questions