[英]Angular directive: ng-model not updated properly when selection changes
我有以下指令:
app.directive('skiTest', function($timeout,$compile) {
return {
'replace': true,
'restrict': 'E',
'scope': {
'data': '=',
'selecto': '@',
'ngModel': '='
},
link: function (scope, element, attrs) {
attrs.$observe("selecto", function () {
$timeout(function () { // we need a timeout to compile after the dust has settled
$compile(element.contents())(scope); //recompile the HTML, make the updated content work.
},0);
});
},
'template':'<div><select name="testSelect" ng-model="ngModel" ng-options="{{selecto}} in data"><option value="">Code</option></select></div>'
}
});
http://jsfiddle.net/L269zgbd/1/
如果我嘗試在指令選擇框中選擇一個國家,則ng-model對象將設置為null。
知道為什么會這樣,如何解決這個問題?
基本上,我希望指令選擇與非指令選擇具有相同的行為。
謝謝!
如果升級小提琴中使用的angular版本,則可以在不使用$compile
或$timeout
情況下進行以下操作
app.directive('skiTest', function () {
return {
'replace': true,
'restrict': 'E',
'scope': {
'data': '=',
'selecto': '@',
'ngModel': '='
},
'template': '<div><select name="testSelect" ng-model="ngModel" ng-options="{{selecto}} in data"><option value="">Code</option></select></div>'
}
});
如果您不能像charlietfl那樣升級angular的版本,建議您改用$ compile函數:
app.directive('skiTest', function($timeout,$compile) {
return {
'replace': true,
'restrict': 'E',
'scope': {
'data': '=',
'selecto': '@',
'ngModel': '='
},
'template':'<div><select name="testSelect" ng-model="ngModel" ng-options="{{selecto}} in data" ng-change="changed()"><option value="">Code</option></select></div>',
compile: function(tElement, tAttributes){
tElement[0].innerHTML = tElement[0].innerHTML.replace('{{selecto}}', tAttributes.selecto);
}
}});
jsfiddle: http : //jsfiddle.net/r366r3b7/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.