Martin Irigaray Martin Irigaray - 3 years ago 147
AngularJS Question

Angular - Add option to select using Jquery

I have a directive that adds new options to a select.

For that i'm using:

let opt: any = angular.element(
'<option value="' + opcion.valor + '">' + opcion.texto + '</option>'
);
this.element.append(this.$compile(opt)(scope));


I don't want to use templates because I don't want a new scope.

The options get added to the list on the view. But when I select some of them, the ng-model of the select doesn't get updated. It gets value null.

How can I make angular to refresh with the new option values?

Here is a codepen example:
Choosing Option X doesn't get reflected on model.

The strange thing is that if i link to angular 1.5.9, it works, but starting with angular 1.6.0 it doesn't.

https://codepen.io/anon/pen/XemqGb?editors=0010

Answer Source

In latest angularJS Select value (read from DOM) is validated

Better to use select's in standard way,

BTW - If you really need this, remove validation by decorating selectDirective as follows

Codepen: https://codepen.io/anon/pen/NapVwN?editors=1010#anon-login

myApp.decorator('selectDirective', function($delegate) {
    let originalCtrl = $delegate[0].controller.pop();
    $delegate[0].controller.push(function() {
      originalCtrl.apply(this, arguments);
      this.hasOption = function() { 
        return true; 
      }
    })
    return $delegate;
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download