So, What I\'m trying to do is fairly simple with vanilla JS, but I\'m using AngularJS and I would like to know how to do it the best way within the framework. I want to upda
ngModel is pretty awesome! If you specify the indexes as a model selectedValues
<select multiple ng-model="selectedValues">
built from your list (selected
) in a $watch
$scope.$watch('selected', function(nowSelected){
// reset to nothing, could use `splice` to preserve non-angular references
$scope.selectedValues = [];
if( ! nowSelected ){
// sometimes selected is null or undefined
return;
}
// here's the magic
angular.forEach(nowSelected, function(val){
$scope.selectedValues.push( val.id.toString() );
});
});
ngModel will automatically select them for you.
Note that this data binding is one-way (selected
to UI). If you're wanting to use the <select>
UI to build your list, I'd suggest refactoring the data (or using another $watch
but those can be expensive).
Yes, selectedValues
needs to contain strings, not numbers. (At least it did for me :)
Full example at http://jsfiddle.net/JB3Un/