ng-selected不起作用

时间:2015-07-20 14:22:01

标签: javascript angularjs

我的问题是ng-selected设置为true,但选项未被选中

这是我的控制器代码

.controller("PendingInvoiceCtrl", function($scope, $location, safeApply, dataService) {
    var userData = dataService.data();
    var mauth_token = userData.mauthToken;
    var mauth_acntId = userData.thisApartment.account;
    var apt_id = userData.thisApartment.id;

    $scope.house_list = userData.thisApartment.house;
    $scope.selectedHouseId = $location.search().houseId;

    console.log($scope.selectedHouseId);
});

这是我的HTML代码

 <select ng-model="selectedHouseId">
      <option ng-repeat="house in house_list" ng-selected="{{ house.house_id == selectedHouseId }}" value="{{ house.house_id }}">
           {{ house.house_display_name }}
      </option>
 </select>

以下是我的数据格式

 {
      house:[0]:{
           house_display_name: "paras, 101",
           house_id: "520755"
      }
 }

4 个答案:

答案 0 :(得分:7)

ng-属性不需要额外的花括号。尝试:

<option ng-repeat="house in house_list" ng-selected="house.house_id == selectedHouseId" ng-value="house.house_id">
    {{house.house_display_name}}
</option>

更好的方法是使用ng-options标记的select可能性。这将导致:

<select
    ng-model="selectedHouseId"
    ng-options="house.house_id as house.house_display_name for house in house_list">
</select>

然后您无需手动担心选项的selected属性,因为它会根据模型的值选择一个属性。

答案 1 :(得分:7)

您的选项标签应为:

<option ng-repeat="house in house_list" ng-selected="house.house_id == selectedHouseId" ng-value="house.house_id">

答案 2 :(得分:2)

我建议您使用Angular Directive ng-options。

<select ng-options="house.house_id as house.house_display_name for house in house_list" ng-model="selectedHouseId"></select>

相关的plunker:http://plnkr.co/8LGz5o0d2gDRoRHYr4pQ

答案 3 :(得分:0)

如果您同时使用ng-Selected和ng-Model,则永远不会真正指定。看起来ng-Model在某种程度上要比ng-Selected优先。