简体   繁体   English

Angular指令:选择更改时,ng-model没有正确更新

[英]Angular directive: ng-model not updated properly when selection changes

I have the following directive: 我有以下指令:

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/ http://jsfiddle.net/L269zgbd/1/

If i'll try to select a country in the directive selection box, the ng-model object is being set to null. 如果我尝试在指令选择框中选择一个国家,则ng-model对象将设置为null。

Any idea why is that and how can i solve this problem? 知道为什么会这样,如何解决这个问题?

Basically i want the same behavior on the directive selection as the one i get with the non directive selection. 基本上,我希望指令选择与非指令选择具有相同的行为。

Thanks! 谢谢!

If you upgrade the version of angular used in the fiddle the following works without using $compile or $timeout 如果升级小提琴中使用的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>'
    }
});

DEMO DEMO

If you can't upgrade your version of angular like charlietfl suggests you can use the $compile function instead: 如果您不能像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/ jsfiddle: http : //jsfiddle.net/r366r3b7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM