简体   繁体   English

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

[英]AngularJS, how do I select the correct default option element?

Problem: Given an array of Person objects, and a separate array of possible names (a super-set containing all the names found within our Person array), how do I set the default option within the generated angular markup (see below). 问题:给定一个Person对象数组和一个单独的可能名称数组(一个超集,其中包含在Person数组中找到的所有名称),如何在生成的角度标记内设置默认选项(请参见下文)。 I'm at a loss as to how to set the item in the names dropdown so that it represents the value of the name in the person object when the UI first loads. 我不知道如何在名称下拉列表中设置项目,以使其在首次加载UI时代表人员对象中名称的值。

在此处输入图片说明

http://plnkr.co/edit/hvIimscowGvO6Hje35RB?p=preview 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>

Perhaps you should consider a sligthly different approach by using ng-repeat on options and ng-selected to denote a selected option: 也许您应该通过在选项上使用ng-repeat和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>

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

A couple changes: 进行了一些更改:

<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 http://plnkr.co/edit/hXGfRZQRz7owxpFZyudB?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM