AngularJS如何访问对象的值

时间:2017-10-29 19:04:36

标签: javascript angularjs json ajax

HTML:

  <div ng-app = "" ng-controller = "personController">
     <p>Persoon: 
        <select ng-model="persoon">
           <option ng-repeat="person in persons">{{person.FirstName}} {{person.FamilyName}}</option>
        </select>
     </p>
     <p>De geboortedatum van <b>{{persoon}}</b> is {{persoon.BirthDate}} en is dus 16 jaar</p>
  </div>

  <script>
     function personController($scope,$http) {
        var persons = "persons.txt";
        var persoon = "";
        $http.get(persons).then( function(response) {
           $scope.persons = response.data;
        });
     }
  </script>

JSON:

[
   {
      "FirstName" : "Harry",
      "FamilyName" : "James",
      "BirthDate" : "29-10-1920"
   }

]

所以我有一个选择框,你可以选择一个人。我想要的是显示那些人的出生日期。 我不知道如何让它发挥作用我尝试了几件事,但没有任何工作。 请帮忙

1 个答案:

答案 0 :(得分:2)

您需要将值设置为 person.BirthDate

 <option  value="{{person.BirthDate}}"  ng-repeat="person in persons">{{person.FirstName}} {{person.FamilyName}}</option>

<强>样本

&#13;
&#13;
 var app = angular.module('myapp',[]);
 app.controller('personController',function($scope){
 $scope.persons = [
   {
      "FirstName" : "Harry",
      "FamilyName" : "James",
      "BirthDate" : "29-10-1920"
   }

];
 });
 
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "myapp" ng-controller = "personController">
     <p>Persoon: 
        <select ng-model="persoon">
           <option  value="{{person.BirthDate}}"  ng-repeat="person in persons">{{person.FirstName}} {{person.FamilyName}}</option>
        </select>
     </p>
     <p>De geboortedatum van <b>{{persoon}}</b> is {{persoon.BirthDate}} en is dus 16 jaar</p>
  </div>
&#13;
&#13;
&#13;

修改

使用ng-options而不是ng-repeat总是更好。

<强>样本

&#13;
&#13;
var app = angular.module('myapp',[]);
 app.controller('personController',function($scope){
 $scope.persons = [
   {
      "FirstName" : "Harry",
      "FamilyName" : "James",
      "BirthDate" : "29-10-1920"
   }

];
 });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "myapp" ng-controller = "personController">
     <p>Persoon: 
        <select ng-model="persoon" ng-options="n.FirstName + ' ' + n.FamilyName for n in persons"></select>
     </p>
     <p>De geboortedatum van <b>{{persoon}}</b> is {{persoon.BirthDate}} en is dus 16 jaar</p>
  </div>
&#13;
&#13;
&#13;