我在这里遗漏了一些明显的东西。在我的指令中,我有一个有效的双向数据绑定,但是我似乎无法使用 $scope.$watch() 来监视指令的父范围 js 对象上可能发生的更改。
如您所见,当我尝试在 attrs.dirModel 上使用 $watch 时,结果值是未定义的,并且没有进一步观察,即使我在短暂延迟后修改了对象。我也尝试过在 $watch 语句中使用(而不是使用)true 标志。
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);
}
}
}
}]);