【发布时间】:2014-12-25 06:23:12
【问题描述】:
我有一个指令(“子”)嵌套在另一个指令(“父”)中。 requires ngModel 和 ngModelCtrl.$modelValue 在其模板中显示并保持最新状态。也就是说,直到我调用 ngModelCtrl.$setViewValue()。
下面是初始化指令的 HTML:
<div parent>
<div child ng-model="content">Some</div>
</div>
以下是指令:
angular.module('form-example2', [])
.controller('MainCtrl', function($scope){
$scope.content = 'Hi';
})
.directive('parent', function() {
return {
transclude: true,
template: '<div ng-transclude></div>',
controller: function(){
},
scope: {}
};
})
.directive('child', function() {
return {
require: ['ngModel', '^parent'],
transclude: true,
template: '<div>Model: {{model.$modelValue}} (<a style="text-decoration: underline; cursor: pointer;" ng-click="alter()">Alter</a>)<br />Contents: <div style="background: grey" ng-transclude></div></div>',
scope: {},
link: function(scope, elm, attrs, ctrl) {
var ngModelCtrl = ctrl[0];
var parentCtrl = ctrl[1];
scope.model = ngModelCtrl;
// view -> model
scope.alter = function(){
ngModelCtrl.$setViewValue('Hi2');
}
// model -> view
// load init value from DOM
}
};
});
当模型(即content)发生变化时,可以在子指令中看到这种变化。当您单击“Alter”链接(触发 $setViewValue() 调用)时,模型的值应变为“Hi2”。这在 child 指令内正确显示,但不在指令外的模型中显示。此外,当我现在在指令外更新模型时,它不再在指令内更新。
怎么会?
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope angular-ngmodel