在我的控制器中,我有一个:
$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>
当我在选择的HTML元素中选择其中一个时,我想在某个地方显示每个信息。有没有办法绑定对象?
在选择框上使用ng-options,然后给它一个ng模型。当选择更改时,模型将持有选定项目表示的对象。
之后,只需使用模型显示
<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>
而 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;
}
})
};
小提琴在这里(对不起,可变名称;)