Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 461
Martin Irigaray Avatar asked Sep 17 '17 18:09

Martin Irigaray


Video Answer


1 Answers

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;
});
like image 106
Andrii Muzalevskyi Avatar answered Nov 11 '22 18:11

Andrii Muzalevskyi