我正在尝试创建一个指令,该指令将根据属性值将 ngModel 属性添加到标签。例如:
angular.module('myModule').
directive('myDirective', function() {
return {
link: function(scope, elem, attrs) {
var modelName = 'myPrefix.' + attrs.name;
attrs.$set('ngModel', modelName);
}
};
});
所以这个 html:
<input name="foo" my-directive></input>
编译成
<input name="foo" ng-model="myPrefix.foo" my-directive></input>
它采用输入的名称,附加前缀,并将 ngModel 属性设置为该值。
当我尝试在链接函数中执行此操作时,input
似乎未在 formController 中注册,因此 form.foo
返回未定义。
是否有可能完成我想做的事情?
编辑:
似乎在 HTML 上设置了 ngModel
属性,但它没有在表单中注册,或者 ngModelController 没有被实例化。如果我在范围内查看 ngModel
的值,当我修改输入时它不会改变。
最佳答案
您应该查看 NgModelController
的文档.它会回答你的问题。为了进一步解释,这里是要点:
您可以捕获 link:
函数的第四个参数,这是您的 ng-model
值。您使用该对象来读取和设置模型。
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if( attrs.stripBr && html == '<br>' ) {
html = '';
}
ngModel.$setViewValue(html);
}
}
希望对您有所帮助。
关于javascript - AngularJS - 是否可以更改链接或编译指令中 ngModel 属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19578554/