在ng-options angularjs

时间:2017-09-05 07:34:52

标签: angularjs

<select 
  get-sport
  name="sportId"
  id="sportId"
  ng-model="sm.sport_id"
  ng-change="changeSport()"
  ng-options="sport.sport_id as sport.name for sport in sports track by sport.sport_id"
  ng-required="true">
  <option value="" selected="selected">-- Select Sport--</option>
</select>

return {
        scope : true,
        link : function (scope) {

            scope.spinning = true;
            $http.get('v1/sport')
                .success(success)
                .error(error);

            function success(data){
                scope.sports = data.data;
                scope.spinning = false;
            }

            function error(error) {
                console.log(error);
            }

        }
    };

在我的控制台Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object ]

具有名称的对象:cricket,sport_id:&#39; 1&#39;

进入我的sm.sport_id获取值3它应该等于名称:football,sport_id:3但默认情况下它选择空白值我不明白为什么请提前指导感谢

3 个答案:

答案 0 :(得分:0)

你的答案是here

“你不能将值作为集合的标签与轨道结合起来。你必须选择其中一个。”。

<select ng-model="sport" ng-options="sport as sport.name for sport in sports track by sport.id">

在这种情况下,您只能将所选运动作为您选择的选项而不是

的ID
$scope.sports = [{id: 1, name: 'Cricket'}, {id: 2, name: 'Hockey'}, {id: 3, name: 'Football'}]
    $scope.sport = $scope.sports[0];

答案 1 :(得分:0)

如果要删除选项中的空白,请不要为其初始化值。添加ng-if选项。

<select 
  get-sport
  name="sportId"
  id="sportId"
  ng-model="sm.sport_id"
  ng-change="changeSport()"
  ng-options="sport_id as sport.name for sport in sports track by sport_id"
  ng-required="true">
  <option value="" ng-if="hideOption" selected="selected">-- Select Sport--</option>
</select>

答案 2 :(得分:0)

我自己克服了这一点,sport_id需要将fr4om整数转换为字符串我这样做就像魅力一样