![](/img/trans.png)
[英]AngularJS - how to change the value of ngModel in custom directive?
[英]AngularJS - Is it possible to change the value of ngModel attribute on directive in link or compile?
我正在尝试创建一个指令,该指令将基于属性值将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
返回undefined。
是否有可能完成我想要做的事情?
编辑:
似乎在HTML上设置了ngModel
属性,但它没有在表单中注册,或者没有实例化ngModelController。 如果我查看范围中ngModel
的值, ngModel
在修改输入时它不会更改。
您应该查看NgModelController
的文档。 它会回答你的问题。 有关进一步说明,请参阅以下内容:
您可以捕获link:
的第四个参数link:
function,这是您的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);
}
}
希望有所帮助。
我能够通过使用模板功能来完成目标。 我认为它在链接函数中不起作用,因为它发生在收集了所有指令之后,因此编译器无法识别添加了ngModel
指令。 我不确定为什么它在编译函数中不起作用(即使我将优先级设置为100)。
这是该指令的工作版本:
angular.module('myModule').
directive('myDirective', function() {
return {
replace: true,
template: function(elem, attr) {
var newElem = '<input ng-model="model.' + attr.name + '">';
return newElem;
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.