我正在尝试创建一个自定义组件,该组件在指令内部使用动态 ng-model。
例如,我可以调用不同的组件,例如:
<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';
}
};
});
这个想法是,如果模型发生变化,指令中的文本框也会发生变化,反之亦然。
问题是,我尝试了不同的方法,但完全没有成功,您可以在这里检查其中一种:http://plnkr.co/edit/7MzDJsP8ZJ59nASjz31g?p=preview在此示例中,我期望两个输入中都有值“New”,因为我正在根据指令更改模型并且是双向绑定(bind) (=)。但不知何故没有以正确的方式绑定(bind)。 :(
如果有人对此有所了解,我将非常感激。提前致谢!
最佳答案
类似这样的吗?
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>',
};
});
关于angularjs - 指令内的动态 ng-model 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20672098/