![](/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.