我在这里缺少一些明显的东西.在我的指令中,我有一个工作的双向数据绑定,但是我似乎不能使用$scope.$watch()监视指令的父范围js对象可能发生的更改.
正如你所看到的,当我尝试在attrs.dirModel上使用$watch时,结果值是未定义的,没有任何进一步观察,即使我在短暂的延迟之后修改对象.我也尝试使用(而不是使用)$watch语句中的真实标志.
HTML:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script> <div ng-app="test" ng-controller="MainCtrl"> <dir dir-model="model"></dir> <p>{{model.tbdTwoWayPropA}}</p> </div> <script type="text/ng-template" id="template"> <div class="test-el">{{dirModel.tbdTwoWayPropB}}</div> </script>
JS:
var app = angular.module('test',[]); app.controller("MainCtrl",[ "$scope","$timeout",function($scope,$timeout){ $scope.model = { tbdTwoWayPropA: undefined,tbdTwoWayPropB: undefined,tbdTwoWayPropC: undefined } // TBD Ajax call $timeout(function(){ // alert("Model updated,but $scope.$watch isn't seeing it."); $scope.model.tbdTwoWayPropA = 1; $scope.model.tbdTwoWayPropB = 30; $scope.model.tbdTwoWayPropC = [{ a: 1 },{ a: 2 },{ a: 3 }]; },2000) } ]); app.directive('dir',[ "$timeout",function($timeout) { return { restrict: "E",controller: function($scope){ $scope.modifyTwoWayBindings = function(){ // Two-way bind works $scope.dirModel.tbdTwoWayPropA = 2; } $timeout(function(){ $scope.modifyTwoWayBindings(); },4000); },scope: { dirModel: '=' },template: $("#template").html(),replace: true,link: function($scope,element,attrs) { $scope.$watch( attrs.dirModel,handleModelUpdate,true); // alert(attrs.dirModel); function handleModelUpdate(newModel,oldModel,$scope) { alert('Trying to watch mutations on the parent js object: ' + newModel); } } } }]);
因为你使用’=’,你有一个本地的指令范围属性dirModel.只是看看:
$scope.$watch('dirModel',true);