我正在使用 Angular ui 来 Bootstrap 其模态:
http://angular-ui.github.io/bootstrap/#/modal
我正在打开一个带有 controller
和 templateUrl
的模式:
var modalInstance = $uibModal.open({
animation: true,
templateUrl: $scope.templateUrl,
controller: $scope.controller,
size: 'lg',
resolve: {
formModel: item
}
});
其中 formModel
是我将在模态中使用的模型。
这是模态的 Controller :
app.controller('commentCtrl', ['$scope', '$modalInstance', 'formModel', function ($scope, $modalInstance, formModel) {
$scope.formModel = {};
var loadFormModel = function () {
if (formModel !== undefined) {
$scope.formModel = formModel;
}
};
loadFormModel();
}]);
此模式有子指令,需要将 formModel
的属性传递给它们
模板:
<div>
<child model="formModel.Comment"></child>
</div>
但是 child
是在模态 Controller 加载 formModel
之前创建的。在 child 内部我想使用 model
作为:
app.directive('child', function () {
return {
restrict: 'E',
template: '<textarea ng-model="model"></textarea>',
link: linkFn,
controller: controllerFn,
scope: {
model: '='
}
};
});
编辑:
我发现我可以做到:
<div>
<child model="formModel" property="Comment"></child>
</div>
...
app.directive('child', function () {
return {
restrict: 'E',
template: '<textarea ng-model="model[property]"></textarea>',
link: linkFn,
controller: controllerFn,
scope: {
model: '=',
property: '@'
}
};
});
有没有更好的方法来做到这一点而不需要额外的属性?
编辑2:
我已经找到了错误所在:
http://plnkr.co/edit/kUWYDvjR8YArdqtQRHhi?p=preview
请参阅 fItem.html
,由于某种原因,任何 ng-if
都会导致绑定(bind)停止工作。我已经添加了一个人为的 ng-if='1===1'
进行演示
最佳答案
发生这种情况是因为 ng-if
指令 creates new inherited scope ,所以这个 bug 只是一个常见的范围原型(prototype)继承陷阱。
解决这个问题的最简洁方法是结合使用controllerAs语法和bindToController,避免不良的范围继承副作用是它们最常见的用例。所以会这样
app.directive('fItem', function () {
return {
restrict: 'E',
replace: true,
templateUrl: 'fItem.html',
controller: ['$scope', function ($scope) {
}],
controllerAs: 'vm',
bindToController: true,
scope: {
model: '='
}
};
});
和
<div class="input-group">
<textarea ng-if='1===1' ng-model="vm.model" class="form-control"></textarea>
</div>
关于javascript - 从子指令绑定(bind)到模型,其中模型尚未在编译时解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33876977/