Why Angular ng-options with 'track by' can't selected by id

前端 未结 4 1959
眼角桃花
眼角桃花 2021-01-12 23:57

I have a array of objects that I\'m displaying using ng-options, and set ng-model with id. If i add track by on it, the item can\'t selected, if not add, it wor

4条回答
  •  轮回少年
    2021-01-13 00:25

    According to the documentation of ng-options (rephrased to your example).

    This will work:

    
    
    $scope.country = $scope.countryList[0];
    

    but this will not work:

    
    
    $scope.country = $scope.countryList[0].id;
    

    In both examples, the track by expression is applied successfully to each country in the countryList array. Because the selected option has been set programmatically in the controller, the track by expression is also applied to the ngModel value. In the first example, the ngModel value is countryList[0] and the track by expression evaluates to countryList[0].id with no issue. In the second example, the ngModel value is countryList[0].id and the track by expression evaluates to countryList[0].id.id (which is undefined). As a result, the model value is not matched against any and the

    提交评论

提交回复
热议问题