1

I have a element , which I would like to bind with a model to get/set the value and to populate it from a list using angular 1

The way I have it, I am able to bind it from UI to model, not vice versa, what am I doing wrong?

HTML:

<div ng-controller="MyCtrl">
    <select class="form-control"        
    ng-options="o as o.prop for o in brands"  
    ng-model="selectedBrands" 
    multiple="multiple" 
    >
    </select>
</div>

JS:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.brands = [{
    prop: 1
  }, {
    prop: 2
  }, {
    prop: 3
  }];
  $scope.selectedBrands = [{
    prop: 2
  }];
}

JSFiddle:

http://jsfiddle.net/4L8b7cke/

1 Answer 1

1

Reuse $scope.brands elements, do not create new for selected items, because ngModel watches the model by reference.

$scope.selectedBrands = [$scope.brands[0],$scope.brands[1]];

Update:

By default, ngModel watches the model by reference, not value. This is important to know when binding the select to a model that is an object or a collection.

From ngOptions documentation

Sign up to request clarification or add additional context in comments.

17 Comments

Ah i see. Thanks!
I will accept this answer in ten min (SO wont let me do it right now)
@Matej: for those of us not familiar with Angular (and I include myself in that list) can you explain what the problem was, why it was a problem and how this answer solves that problem? (I accept that "it's magic" might well be the explanation, however.)
From my knowledge i don't find a problem in the question. Could you please explain what was the thing in the question that made you suggest $scope.selectedBrands = [$scope.brands[0],$scope.brands[1]]; as an answer.
@DavidThomas I assumed that Angular binds by reference rather than checking equality on the values being set in the controller with the list possible values.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.