ng-options和ng-model预选值

时间:2016-05-12 06:30:28

标签: javascript angularjs web

我正在尝试使用ng-options预选值。这是什么

 <select ng-model="promocode.PRODUCT" ng-change="getSomething()" ng-options="product as product.NAME for product in products">

问题是默认值选中。我的promocode.PRODUCT对象与ng-options中的对象相同,但角度设置默认值为空。

我的错误在哪里?

3 个答案:

答案 0 :(得分:2)

假设您的产品具有某种id属性,这应该可以解决问题:

 <select ng-model="promocode.PRODUCT"
    ng-change="getSomething()"
    ng-options="product as product.NAME for product in products track by product.id">

track by product.id告诉angular用它们的id属性比较数组项,而不是比较对象之间的相等性。

以下是tracking / ng-options的更多信息。

一个有效的例子:

&#13;
&#13;
var myApp = angular.module('myApp', []);
myApp.controller("controller", function($scope) {
  $scope.products = [{
    id: 1,
    name: 'FirstProduct'
  }, {
    id: 2,
    name: 'SecondProduct'
  }];

  $scope.promocode = {
    product: { // Here I am using a placeholder product to illustrate that 
      id: 2    // the select is identifying the correct row by it's `id`.
    }
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="controller">
  <select ng-model="promocode.product" ng-change="getSomething()" ng-options="product as product.name for product in products track by product.id">
  </select>
  <br/>
  {{promocode.product}}
</div>
&#13;
&#13;
&#13;

更好的选择是选择正确的行,如下所示:

$scope.promocode = $scope.products[1];

然后你不必复制任何数据。

答案 1 :(得分:1)

假设log4j.additivity=falseproduct属性,您需要使用id,阅读DOCs

select as label group by group for value in array track by trackexpr

jsFiddle

答案 2 :(得分:0)

试试这个..

<select ng-model="promocode.PRODUCT"
    ng-change="getSomething()"
    ng-options="product as product.NAME for product in products track by product.ID">
    <option selected disabled>{{Your default value}}</option>
 </select>