AngularJS绑定一个对象

时间:2015-05-09 03:46:02

标签: javascript angularjs

在我的控制器中我有这个:

ObjectId()

我在我的视图中显示它们:

$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 html元素中选择其中一个时,我想在某个地方显示每个信息。有没有办法绑定对象?

2 个答案:

答案 0 :(得分: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>

<强>演示

&#13;
&#13;
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];
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分: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 (抱歉变量名称;))