Dfr
Dfr

Reputation: 4185

Angularjs selectbox not reflecting underlying ng-model when using ng-bind-html

This is could look like something near to exotic at first sight, but main point of doing it this way is to stylize selectbox nicely with optgroups and colors.

Here is simplified example of markup:

<select ng-model="query.Statuses" multiple="" ng-bind-html="to_trusted(opts)">
</select>

and controller:

app.controller('MainCtrl', function($scope, $sce) {
  $scope.to_trusted = function(html_code) {  return $sce.trustAsHtml(html_code); };

  $scope.opts = '<option value="Draft">Draft</option>'+
      '<option value="Pending">Pending</option>'+
      '<option value="Live">Live</option>'+
      '<option value="Deleted">Deleted</option>';

  $scope.query = {
      Statuses: ["Pending","Live"]
   };
});

And here is plunker: http://plnkr.co/edit/Kv5xkl1KQVxgwGfnVpeZ?p=preview

As you can see the desired two options are not selected.

Upvotes: 0

Views: 79

Answers (3)

ryeballar
ryeballar

Reputation: 30118

Instead of using ng-bind-html or ng-repeat why not stick with how AngularJS is doing it using select's ng-option directive?

FORKED DEMO

HTML

<select ng-model="query.Statuses" multiple
      ng-options="status for status in statuses"></select>

JAVASCRIPT

app.controller('MainCtrl', function($scope) {
  $scope.statuses = ['Draft', 'Pending', 'Live', 'Archived', 'Deleted'];
  $scope.query = { Statuses: ["Pending","Live"] };
});

Alternatively, if you wish to have a complex set options wherein you need some styling or disabling of options then you can use ng-repeat and ng-selected at the same time.

DEMO

HTML

<select ng-model="query.Statuses" multiple>
  <option ng-repeat="status in statuses" value="{{status}}" ng-bind="status"
    ng-selected="query.Statuses.indexOf(status) >= 0"></option>
</select>

Upvotes: 0

loujaybee
loujaybee

Reputation: 96

Why not run your options inside an ng-repeat?

 $scope.opts = ['Draft', 'Live']; // etc

then in your html

<option value="opt" ng-repeat="opt in opts">{{opt}}</option>

Instead of using ng-model, set an on blur or on change event that triggers a function to manipulate your scope array as you wish

Upvotes: 1

Nicola Ferraro
Nicola Ferraro

Reputation: 4189

Setting HTML code in your controller is not a good practice. You have to separate view and controller code. Try to include a template option tag in your view with ng-repeat and set the options in your controller with javascript objects or associative arrays.

You can also use ng-options in the select tag as explained here: https://docs.angularjs.org/api/ng/directive/select

Upvotes: 0

Related Questions