角度指令:当选择更改时,ng 模型未正确更新
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/
相关文章:
- 如何将ng选项的索引作为angularJs中的值传递给模型
- 角度无线电按钮ng模型不起作用
- ng模型内的ng重复的ng重复开始
- 将输入值设置为ng模型属性[Angular]时出现问题
- 自定义指令中的AngularJS ng模型
- 如何为动态创建的文本区域中输入的值更新ng模型
- ng重复中的ng模型-初始化唯一作用域属性
- ng重复变量到ng模型
- 初始化ng模型时,Angular ui选择占位符不起作用
- 角度去抖动(ng模型选项)不起作用
- 即使 ng 模型有值,也使输入字段为空
- 选择框中带有关联的ng模型,选项中带有ng重复
- 为什么我的指令(使用链接)没有出现,并允许ng模型看到它
- NG-重复中断指令模型绑定
- AngularJS+IE 11+聚合物=ng模型未更新
- ng模型在$(element).clone()之后不起作用
- 为什么ng选项指令需要ng模型
- AngularJS ng下拉树结构的模型定义
- AngularJS:如何将视图中指定的模型(ng-bind)绑定到通过API可用的$资源
- 内有角度单选按钮模型ng重复