AngularJS,如何选择正确的默认选项元素?

时间:2014-07-26 15:32:02

标签: javascript angularjs

问题: 给定一个Person对象数组,以及一个单独的可能名称数组(包含在Person数组中找到的所有名称的超集),如何在生成的角度标记中设置默认选项(见下文)。 我不知道如何在名称下拉列表中设置项目,以便它在UI首次加载时表示person对象中名称的值。

enter image description here

http://plnkr.co/edit/hvIimscowGvO6Hje35RB?p=preview

<!DOCTYPE html>
<html>

<head>
<script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<button ng-click="loadData()">Load Data</button>

<ul ng-repeat="person in model.persons" >
  <li>name: {{person.name}}
    <select ng-select
            ng-options="item.name for item in data"
            ng-change="updateName(selectedName)"
            ng-model="selectedName">
    </select>
  </li>
  <li>age : {{person.age}}</li>
  <li>sex : {{person.sex}}</li>
</ul>

<script>

  var app=angular.module("app",[]);

  app.controller("test",function($scope){
    $scope.model={};
    $scope.model.persons=[];
    $scope.updateName=function(item){
      this.person.name = item.name;
    }
    $scope.data=[{name:'bob'},{name:'Sal'},{name:'Lee'},{name:"Fred"}];

    $scope.loadData=function(){

      $scope.model.persons=[{name:'bob',age:24,sex:'Yes Please'},
                      {name:'Sal',age:29,sex:'Not Today'},
                      {name:'Lee',age:34,sex:'If I must'}];

    }

  });

  angular.bootstrap(document,["app"]);

</script>

2 个答案:

答案 0 :(得分:2)

也许您应该考虑使用ng-repeat on options和ng-selected来表示选择的选项,这是一种不同的方法:

<select ng-model="person.name">
    <option
            ng-repeat="item in data"
            ng-selected="item.name == person.name"
            ng-model="person.name">
        {{item.name}}
    </option>
</select>

请在此处查看:http://plnkr.co/edit/gOO3iTXFFNWzFVMZv9GJ?p=preview

答案 1 :(得分:1)

一些改变:

<ul ng-repeat="person in model.persons" ng-init="selectedName = person.name">

ng-options="item.name as item.name for item in data"

http://plnkr.co/edit/hXGfRZQRz7owxpFZyudB?p=preview