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

前端 未结 4 1955
眼角桃花
眼角桃花 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:29

    This Is basically how track by work. track by can only work with object not with any property of the object. and without track by it will work with a separate property not with entire object. Check the code part.

    Some lines from Angular js track by (read it for better understanding)

    This will work:

      $scope.selected = $scope.items[0];
    

    but this will not work:

     $scope.selected = $scope.items[0].subItem;
    

    angular.module('myApp', [])
      .controller('MyController', ['$scope', function ($scope) {
        $scope.countryList = [{id: 1, name: 'China'}, {id: 2, name: 'America'}, {id: 3, name: 'England'}]
        $scope.country = {id: 1, name: 'China'};
       $scope.countryID = 1;
      }]);
    
    

    no track by

    {{country}}

    have track by, can't selected by id

    {{country}}

    no track by

    {{countryID}}

    have track by, can't selected by id

    {{countryID}}

提交回复
热议问题