Setting the selected item in angularJS select directive

后端 未结 4 1455
既然无缘
既然无缘 2021-02-05 07:04

I have a problem with setting the selected item in angular\'s select directive. I don\'t know if this is a bug or a conscious design from the designers of angular. It sure makes

4条回答
  •  不知归路
    2021-02-05 07:30

    The reason it doesn't work is that angular expects the objects references to be equal. In your case (the 'select from object' in your plnkr) creates a new object, albeit with the same properties. However, Angular can't know that two different objects represents the same object. You have at least two approaches:

    Find the correct city object instance

    Instead of setting $scope.customer.city to a new object, find the actual city object from the $scope.cities array. If you're using UnderscoreJs you could do something like:

    $scope.customer.city = _.find($scope.cities, function (city) {
        return city.id === theCustomersCity.id;
    });
    

    Bind to the city id instead of the city object

    Another approach, which might be easier, is to change the ng-model and ng-options directives to match on id instead of object. See working example here.

    
    

提交回复
热议问题