AngularJS,我怎么选择正确的默认选项元素? [英] AngularJS, how do I select the correct default option element?

查看:88
本文介绍了AngularJS,我怎么选择正确的默认选项元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:
鉴于Person对象数组,可能的名字的一个单独的数组(包含我们所有的人阵中找到名字的超集),我怎么产生的角标记中设置默认选项(见下文)。
我在一个不知如何设置项目中的名称下拉,使其重新presents名称的价值在人的对象的时候,UI首次加载。

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). 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.

http://plnkr.co/edit/hvIimscowGvO6Hje35RB?p=$p$ PVIEW

<!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>

推荐答案

一对夫妇的变化:

<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=$p$ PVIEW

这篇关于AngularJS,我怎么选择正确的默认选项元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆