12
我在这里丢失了一些明显的东西。在我的指令中,我有一个可用的双向数据绑定,但是我似乎无法使用$ scope。$ watch()来监视指令的父范围js对象上可能发生的更改。
正如你所看到的,当我尝试使用$上attrs.dirModel观看所产生的价值是不确定的,并没有进一步看,即使我修改短暂延迟后的对象。我也试过在$ 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);
}
}
}
}]);
谢谢。你碰巧知道了解更多关于“本地指令范围属性”的好资源。以前我只能看到访问attributes参数的例子。 最终的JS小提琴供用户参考。 http://jsfiddle.net/Kzwu7/8/ – BradGreens 2013-03-11 18:15:43
@BradGreens,好吧,它在不太容易理解的[指令页面](http://docs.angularjs.org/guide/directive )在“指令定义对象”部分下。另请参阅http://stackoverflow.com/questions/14050195/what-is-the-difference-between-and-in-directive-scope/14063373#14063373,http://stackoverflow.com/questions/14908133/what- is-the-difference-between-vs-in-in-angularjs,和http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs/14049482#14049482(请参阅底部附近的“指令”部分)。 – 2013-03-11 18:29:11
我读过很多遍了;)。我想现在我特别想知道哪些角度方法会接受该属性的字符串表示作为参数。即$ observe('attr',fct),$ set('attr','val'),$ watch('attr',fct)等等......字符串表示有点神奇。 – BradGreens 2013-03-11 18:58:46