2016-03-07 86 views
0

我正在寫一個自定義指令,其範圍內有單個字段。該字段是一個包含值的數組字典。自定義角度指令:如何監視範圍變化

我想該指令對這一領域做出的任何變化做出反應:新條目,在列表中的附加價值,等等

我只是想弄清楚爲什麼:

  • 當我更改字典中的值時,我的指令不反應。
  • 指令甚至沒有初始化字典的初始化。

這裏是我的腳本,在這裏我只在子directive.Nothing執行一些日誌點擊字典當按鈕被修改情況的一個簡化版本:

<!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>

我試過使用$ watch,$ watchCollection,深入觀察,但它似乎沒有完成這項工作。

+0

您認爲如何將某些東西存儲到作用域的「myDico」字段中?爲什麼? –

回答

2

您在指令定義對象中缺少範圍綁定定義。

scope: { 
    myDico: '=' 
} 
+2

請注意,即使已添加,代碼也必須更改爲'