无法从我的控制器Angular JS中设置选择值

时间:2014-08-20 13:13:22

标签: javascript angularjs select angularjs-scope

From this example

我正在尝试从我的控制器设置选择值,这对我来说不起作用,即使我在这里设置了许多问题中解释的id。唯一的区别是我有一个使用ng-init设置的默认值。如何设置控制器的值?

DOM:

<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)">
    <option value="0">-- All orders --</option>
    <option ng-repeat="obj in orders" value="{{ obj.id }}">{{ obj.name }}</option>
</select>

JS函数内部:

$scope.orders = data;
$scope.storeorder = parseInt($scope.order); // Tried without parseInt also

console.log($scope.storeorder)返回正确的值,但它没有在浏览器DOM中设置正确的值。

3 个答案:

答案 0 :(得分:2)

如果您不想使用ng-options(这是正确的方法),您可以尝试使用

ng-selected : Working Demo : http://jsfiddle.net/nf2m0rr1/

Example : 

 <body ng-app ng-controller="OrderCtrl">
   <div>Order is: {{storeorder}}</div>
   <select ng-model="storeorder">
     <option ng-selected="{{order.value == storeorder}}" ng-repeat="order in orders"   value="{{order.value}}">{{order.displayName}}</option>
   </select>
 </body>

 function OrderCtrl($scope) {
  $scope.storeorder = 2;

  $scope.orders = [{
    value: '1',
    displayName: 'Order One'
  }, {
    value: '2',
    displayName: 'Order Two'
  }]
}

答案 1 :(得分:0)

使用ng-options

<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)" ng-options="obj.id as obj.name for obj in orders">

答案 2 :(得分:0)

ng-options解决了50%的问题,但我仍然需要处理DOM中的默认值并更改ng-init选项。这真让我烦恼。这是完整的解决方案,使我无法从控制器中设置任何内容:

<select ng-model="storeorder" ng-options="orderdata.id as orderdata.name for orderdata in orders" ng-init="storeorder = order == 0 ? 0 : order" ng-if="orders.length > 0" ng-change="storeOrderChange(storeorder)">
    <option value="">-- All orders --</option>
</select>