角度指令:当选择更改时,ng 模型未正确更新

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

本文关键字:模型 ng 更新 指令 选择      更新时间:2023-09-26

我有以下指令:

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/