David
David

Reputation: 1136

Custom angular directive : how to watch for scope changes

I am writing a custom directive with a single field in its scope. This field is a dictionary with arrays in values.

I want the directive to react to any change made on this field : new entry, additional value in list, etc...

I'm just trying to figure out why :

Here is a simplified version of my script, where I only perform some logging in the sub-directive.Nothing happens when the button is clicked on the dictionary is modified :

<!DOCTYPE html>
    <html>

    <head>
      <meta charset="UTF-8">
      <title>Test</title>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      <script>
        angular.module("myApp", [])

        .controller("myCtrl", function($scope) {
          $scope.dico = {};
          $scope.dico["Paris"] = [];
          $scope.dico["Paris"].push("Tour Eiffel");
          $scope.dico["Paris"].push("Champs Elysees");
          $scope.dico["London"] = [];
          $scope.dico["London"].push("British Museum");

          $scope.addPOI = function() {
            $scope.dico["Wellington"] = [];
            $scope.dico["Wellington"].push("Botanic Garden");
            console.log($scope.dico);
          };
        })

        .directive('subdirective', function() {
          return {
            restrict: 'E',
            template: '<div><span ng-repeat="key in myDico">{{key}}</span></div>',
            link: function(scope, element, iAttrs) {
              console.log("test");
              scope.$watch("myDico", function(newVal, oldVal) {
                console.log("watch!");
                console.log(newVal);
                //update values...
              }, true);
            },
            scope: {
              myDico: '='
            }
          };
        });
      </script>
    </head>

    <body ng-app="myApp">
      <div ng-controller="myCtrl">
        <button ng-click="addPOI()">
          Add POI
        </button>
        <div>
          <subdirective myDico="dico"></subdirective>
        </div>
      </div>
    </body>

    </html>

I have tried to use $watch, $watchCollection, deep watch, but it does not seem to do the job.

Upvotes: 0

Views: 80

Answers (1)

Prashant
Prashant

Reputation: 8040

You are missing scope binding definition in your Directive Definition Object.

scope: {
    myDico: '='
}

Upvotes: 2

Related Questions