2015-10-14 130 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