2015-05-09 84 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 (很抱歉的變量名;))

相關問題