Reputation: 2639
In my controller I have this:
$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,
}
]
And I'm showing them in my View doing this:
<select name="" id="">
<option ng-repeat="p in participants">{{ p.name }}</option>
</select>
I want to show each one information in some place when I select one of them in the select html element. Is there a way to bind the object?
Upvotes: 2
Views: 44
Reputation: 8488
While ng-options
is better, this is your way:
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;
}
})
};
Fiddle Here (Sorry for the variable names ;))
Upvotes: 0
Reputation: 42736
Use ng-options on your select box, and give it a ng-model. When the select is changed the model will hold the object represented by the selected item.
After that just use the model to display
<select ng-model="currentItem"
ng-options="participant.name for participant in participants">
</select>
<div>
{{currentItem.name}}<br/>
{{currentItem.birthday}}<br/>
{{currentItem.takePart}} </div>
</div>
Demo
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>
Upvotes: 2