简体   繁体   中英

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/

If i'll try to select a country in the directive selection box, the ng-model object is being set to 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

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

If you can't upgrade your version of angular like charlietfl suggests you can use the $compile function instead:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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