Fizk
Fizk

Reputation: 1114

What is the right way to select by value in a dropdown?

I'm having a bit of an issue with Angular and selecting an item from a dropdown and making Angular update the model.

I've been searching through StackOverflow, but only with partial luck.

The problem is that when i'm manually setting a value on a model, my dropdown updates correct, but the model itself does not update;

$scope.setSelected = function(){
    $scope.selected.id = 15;
    //$scope.$apply();// $apply already in progress
}

From various answers on StackOverflow, I've found out that Angular does not know about this update and the suggested answer is to run either a $scope.$apply() or a $scope.$digest(), but both throw a $apply already in progress exception. I have a feeling that this is not the correct way for me to do it, since it doesn't make sense, that you have to trigger an event to select by value.

What is the correct way to select an item in a dropdown by a given value?

Full code example can be found at https://jsfiddle.net/c2x3jvut/

When clicking the "Select dinnerman" button, the dropdown updates correct, but the shown model and when clicking "Log selected" it only shows the selected model, but with an updated id.

Upvotes: 1

Views: 49

Answers (4)

Romesh
Romesh

Reputation: 2274

You can use $filter to get whole object instead of each property.

$scope.setSelected = function(){
    $scope.selected = $filter('filter')($scope.persons,15,'id')[0];
    //$scope.selected.id = 15;
    //$scope.$apply();// $apply already in progress
  }

Here is the modified version

Upvotes: 1

Naveen
Naveen

Reputation: 830

You are just updating the current model with an ID. But when you see carefully the name and age remains same. Further you need to update the whole object as below:

$scope.setSelected = function(){
    $scope.selected.id = 15;
    $scope.selected.name = "Dinner-man";
    $scope.selected.age = 20;
  }

Or anyother way to directly updates the object.

Upvotes: 0

FDavidov
FDavidov

Reputation: 3675

Not sure I understand your question, but still...

You may include in each entry of the dropdown:

...ng-click="setSelected(<value>)"...

and, of course, add a parameter to the function.

By the way, are you aware that in the fiddle example you are selecting ID 15 in function setSelected?

Upvotes: 0

Brian
Brian

Reputation: 7654

ng's select binds its value based on its ngModel, which is being manipulated incorrectly in the example. The correct method is to change the reference of the ngModel rather than the select's id:

$scope.setSelected = function () {
    $scope.selected = $scope.persons[1];  // yes
    // $scope.selected.id = 15;  // no
};

Fiddle might have been updated to show the effects.

Upvotes: 1

Related Questions