2015-05-09 65 views
2

在我的控制器我有这样的:AngularJS绑定的对象

$scope.participants = [ 
    { 
     name: "Alan", 
     birthday: new Date("1991/01/21"), 
     takePart: true, 
    }, 
    { 
     name: "Leandro", 
     birthday: new Date("1991/01/21"), 
     takePart: true, 
    }, 
    { 
     name: "Alejandro", 
     birthday: new Date("1991/03/21"), 
     takePart: true, 
    } 
] 

而且我向他们展示我认为这样做:

<select name="" id=""> 
    <option ng-repeat="p in participants">{{ p.name }}</option> 
</select> 

我想表明在一些地方每一个信息当我在select html元素中选择其中的一个时。有没有办法绑定对象?

+2

看ngOptions https://docs.angularjs.org/api/ng /指令/ ngOptions – Chandermani

回答

2

在您的选择框中使用ng-options,并给它一个ng-model。当选择被改变时,模型将保存所选项目表示的对象。

后,只是使用模型来显示

<select ng-model="currentItem" 
     ng-options="participant.name for participant in participants"> 
</select> 
<div> 
    {{currentItem.name}}<br/> 
    {{currentItem.birthday}}<br/> 
    {{currentItem.takePart}} </div> 
</div> 

演示

var app = angular.module("test",[]); 
 
app.controller("Test",function($scope){ 
 
    $scope.participants = [ 
 
    { 
 
     name: "Alan", 
 
     birthday: new Date("1991/01/21"), 
 
     takePart: true, 
 
    }, 
 
    { 
 
     name: "Leandro", 
 
     birthday: new Date("1991/01/21"), 
 
     takePart: true, 
 
    }, 
 
    { 
 
     name: "Alejandro", 
 
     birthday: new Date("1991/03/21"), 
 
     takePart: true, 
 
    } 
 
    ]; 
 
    $scope.currentItem = $scope.participants[0]; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="test" ng-controller="Test"> 
 
    <select ng-model="currentItem" ng-options="participant.name for participant in participants"> 
 
     
 
    </select> 
 
    <div> 
 
    {{currentItem.name}}<br/> 
 
    {{currentItem.birthday}}<br/> 
 
    {{currentItem.takePart}} </div> 
 
    </div>

0

虽然ng-options比较好,这是你的方式:

HTML:

<select name="" ng-model="test" ng-change="hello()" id=""> 
    <option ng-repeat="p in participants">{{ p.name }}</option> 
</select> 
    <p>{{pt.name}} - {{pt.birthday}} - {{pt.takePart}}</p> 

JS:

 $scope.participants = [ 
    { 
     name: "Alan", 
     birthday: new Date("1991/01/21"), 
     takePart: true, 
    }, 
    { 
     name: "Leandro", 
     birthday: new Date("1991/01/21"), 
     takePart: true, 
    }, 
    { 
     name: "Alejandro", 
     birthday: new Date("1991/03/21"), 
     takePart: true, 
    } 
] 
    $scope.test=$scope.participants[0].name; 
    $scope.pt=$scope.participants[0]; 
    $scope.hello = function(){ 
     angular.forEach($scope.participants, function(item){ 
      if(item.name==$scope.test){ 
       $scope.pt = item; 
      } 
     }) 
    }; 

小提琴Here (很抱歉的变量名;))