我有一个在该视图中使用父范围的指令。该指令有一个使用隔离范围的子指令。我试图让父指令观察对子指令的 ngModel 所做的任何更改,并在进行更改时更新其自己的模式。这是一个可能解释得更好的 jsfiddle:http: //jsfiddle.net/Alien_time/CnDKN/
这是代码:
<div ng-app="app">
<div ng-controller="MyController">
<form name="someForm">
<div this-directive ng-model="theModel"></div>
</form>
</div>
</div>
Javascript:
var app = angular.module('app', []);
app.controller('MyController', function() {
});
app.directive('thisDirective', function($compile, $timeout) {
return {
scope: false,
link: function(scope, element, attrs) {
var ngModel = attrs.ngModel;
var htmlText = '<input type="text" ng-model="'+ ngModel + '" />' +
'<div child-directive ng-model="'+ ngModel + '"></div>';
$compile(htmlText)(scope, function(_element, _scope) {
element.replaceWith(_element);
});
// Not sure how to watch changes in childDirective's ngModel ???????
}, // end link
} // end return
});
app.directive('childDirective', function($compile, $timeout) {
return {
scope: {
ngModel: '='
},
link: function(scope, element, attrs, ngModel) {
var htmlText = '<input type="text" ng-model="ngModel" />';
$compile(htmlText)(scope, function(_element, _scope) {
element.replaceWith(_element);
});
// Here the directive text field updates after some server side process
scope.ngModel = scope.dbInsertId;
scope.$watch('dbInsertId', function(newValue, oldValue) {
if (newValue)
console.log("I see a data change!"); // Delete this later
scope.ngModel = scope.imageId;
}, true);
},
} // end return
});
在示例中,您可以看到在父指令及其子指令中都有一个文本输入。如果您在每个模型中键入,则另一个模型会更新,因为它们是由ngmodel
. 但是,子指令的文本输入会在服务器连接后更新。发生这种情况时,父指令中的文本输入不会更新。所以我认为我需要观察子指令中的 ngModel 是否有任何变化。我怎样才能做到这一点?是否有意义?