指令内的动态 ng-model 绑定 [英] Dynamic ng-model binding inside a directive
问题描述
我正在尝试创建一个自定义组件,该组件使用由内而外的动态 ng-model 指令.
I'm trying to create a custom component that uses a dynamic ng-model inside-out the directive.
例如,我可以调用不同的组件,例如:
As an example, I could invoke different components like:
<custom-dir ng-model="domainModel1"></custom-dir>
<custom-dir ng-model="domainModel2"></custom-dir>
使用如下指令:
app.directive('customDir', function() {
return {
restrict: 'EA',
require: '^ngModel',
scope: {
ngModel: '=dirValue',
},
template: '<input ng-model="dirValue" />',
link: function(scope, element, attrs, ctrl) {
scope.dirValue = 'New';
}
};
});
这个想法是,如果模型发生变化,指令中的文本框也会发生变化,反之亦然.
The idea is that the textbox from the directive would change if the model changes, and in the other way around.
问题是我尝试了不同的方法但根本没有成功,您可以在此处查看其中一个:http://plnkr.co/edit/7MzDJsP8ZJ59nASjz31g?p=preview 在这个例子中,我希望在两个输入中都有值New",因为我正在从指令和是一个双向边界 (=).但不知何故并没有以正确的方式绑定.:(
The thing is that I've tried different approaches with no success at all, you can check one of this here: http://plnkr.co/edit/7MzDJsP8ZJ59nASjz31g?p=preview In this example, I'm expecting to have the value 'New' in both of the inputs, since I'm changing the model from the directive and is a bi-directional bound (=). But somehow is not bound in the right way. :(
如果有人对此有所了解,我将不胜感激.提前致谢!
I will be really grateful if someone give some light on that. Thanks in advance!
推荐答案
类似的事情?
http://jsfiddle.net/bateast/RJmhB/1/
HTML:
<body ng-app="test">
<my-dir ng-model="test"></my-dir>
<input type="text" ng-model="test"/>
</body>
JS:
angular.module('test', [])
.directive('myDir', function() {
return {
restrict: 'E',
scope: {
ngModel: '='
},
template: '<div><input type="text" ng-model="ngModel"></div>',
};
});
这篇关于指令内的动态 ng-model 绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!