Angularjs watch for change in parent scope

前端 未结 5 1722
甜味超标
甜味超标 2020-12-24 05:32

I\'m writing a directive and I need to watch the parent scope for a change. Not sure if I\'m doing this the preferred way, but its not working with the following code:

5条回答
  •  既然无缘
    2020-12-24 05:53

    Alright that took me a while here's my two cents, I do like the event option too though:

    Updated fiddle http://jsfiddle.net/enU5S/1/

    The HTML

    The JS

    angular.module("myApp", []).directive('awesomeSauce',function($window){
      return {
        restrict : "A",
          template: "
    Ch-ch-ch-changes: {{count}} {{someData}}
    ", scope: {someData:"="}, link : function(scope,elem,attrs){ scope.count=0; scope.$watch("someData",function() { scope.count++; }) } }; }).controller("MyCtrl", function($scope){ $scope.model = {someProperty: "something here"); });

    What I'm showing here is you can have a variable that has two way binding from the child and the parent but doesn't require that the child reach up to it's parent to get a property. The tendency to reach up for things can get crazy if you add a new parent above the directive.

    If you type in the box it will update the model on the controller, this in turn is bound to the property on the directive so it will update in the directive. Within the directives link function it has a watch setup so anytime the scope variable changes it increments a counter.

    See more on isolate scope and the differences between using = @ or & here: http://www.egghead.io/

提交回复
热议问题