2015-10-14 150 views
0

我想弄清楚如何更改菜單中選擇的選項,由AngularJS:通過值設置默認選擇的選項

實施例:

HTML

<div data-ng-app="myApp"> 
    <div data-ng-controller="myController"> 
     <p>n_images = {{n_images}}</p> 
     <select data-ng-model="n_images"> 
      <option data-ng-selected="{{o.value == n_images}}" 
        data-ng-repeat="o in n_images_options" 
        value="{{o.value}}">{{o.text}}</option> 
     </select> 
    </div> 
</div> 

的JavaScript

'use strict'; 

var myApp = angular.module('myApp', []); 

myApp.controller('myController', ['$scope', 
    function($scope) { 
     $scope.n_images = 4; 

     $scope.n_images_options = [ 
      {value: 1, text: "1 image"}, 
      {value: 2, text: "2 images"}, 
      {value: 3, text: "3 images"}, 
      {value: 4, text: "4 images"}, 
      {value: 5, text: "5 images"}, 
      {value: 6, text: "6 images"}, 
      {value: 7, text: "7 images"}, 
      {value: 8, text: "8 images"} 
     ]; 
    } 
]); 

這適用使用AngularJS 1.1.5(JSFiddle example)。

然而,它在AngularJS的較新版本工作,如 1.4.6版(JSFiddle example)。

如何更改使用某個值選擇了哪個選項?我正在嘗試創建一個選擇菜單,該菜單將通過URL中的查詢字符串值進行初始化。

回答

1

爲了達到最佳效果,你需要使用ng-options

<select data-ng-model="n_images" ng-options="o.value as o.text for o in n_images_options"> 
</select> 

https://jsfiddle.net/eywLkdub/

+0

謝謝!儘管我遇到了另一個我能解決但不明白的問題 - 使用$ location.search()從查詢字符串獲取n_images並將其添加到$ scope,以便選擇菜單正在選擇正確的選項,這隻適用於如果我使用parseInt()將n_images轉換爲整型(我假設它是類型字符串)。 – Bill

+1

據我所知你必須使用'ui-router'來創建它,所以你不需要'parseInt':https://github.com/angular-ui/ui-router/wiki/URL -路由 – sirrocco