AngularJS根据所选项目从json动态填充详细信息

时间:2014-06-12 01:22:06

标签: javascript json angularjs angularjs-ng-repeat

我正在尝试创建一个页面,其中列表组中的项目很少,选中后应显示更多详细信息。

请在此处查看示例http://plnkr.co/edit/Oava3pA9OTsm80K58GdT?p=preview

如何根据列表组中选择的项目填充json文件中的详细信息?

这是我到目前为止所拥有的。

HTML:

<div ng-controller=ItemsController>
    <h3>Test</h3>
    <div class="row">
      <div class="col-md-4">
        <div class="panel panel-default">
          <ul class="list-group">
            <a class="list-group-item" ng-repeat="item in itemDetails">{{item.name}}</a>
          </ul>
        </div>
      </div>

      <div class="col-md-8">
        <div class="panel panel-default">
          <h2>Name: </h2>
          <br />Address Line 1:
          <br />Address Line 2:
          <br />Suburb:
          <br />Phone:
          <br />Email:
        </div>
      </div>
    </div>
  </div>

脚本:

var myItemsApp = angular.module('myItemsApp', []);

myItemsApp.factory('itemsFactory', ['$http', function($http){
  var itemsFactory ={
    itemDetails: function() {
      return $http(
      {
        url: "mockItems.json",
        method: "GET",
      })
      .then(function (response) {
        return response.data;
        });
      }
    };
    return itemsFactory;

}]);


myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory', function($scope, itemsFactory){
  var promise = itemsFactory.itemDetails();

    promise.then(function (data) {
        $scope.itemDetails = data;
        console.log(data);
    });
}]);

JSON:

[
   {
      "$id":"1",
      "name":"Test itemName 1",
      "themeName":"ASD",
      "addressLine1":"18 Banksia Street",
      "addressLine2":null,
      "suburb":"Heidelberg",
      "state":"VIC",
      "postalCode":"3084",
      "contactPhone":"+61 3 123456",
      "emailAddress":"qwerty.it@xyz.com"
   },
   {
      "$id":"2",
      "name":"Test itemName 2",
      "themeName":"WER",
      "addressLine1":"11 Riverview Place",
      "addressLine2":"Metroplex on Gateway",
      "suburb":"Murarrie",
      "state":"QLD",
      "postalCode":"4172",
      "contactPhone":"1300 73123456",
      "emailAddress":"asdfg.it@xyz.com"
   },
   {
      "$id":"3",
      "name":"Test itemName 3",
      "themeName":"ERT",
      "addressLine1":"60 Waterloo Road",
      "addressLine2":null,
      "suburb":"North Ryde",
      "state":"NSW",
      "postalCode":"2113",
      "contactPhone":"123456",
      "emailAddress":"zxcvb.it@xyz.com"
   }
]

非常感谢任何帮助。

我是编程新手。如果我做错了,也请随意采用其他方法实现这一目标。

1 个答案:

答案 0 :(得分:9)

您可以使用ng-click指令指定单击某些内容时发生的情况。

所以我使用函数($scope.selected)将点击的项目分配给$scope.select(item)对象,然后将该对象的属性绑定到您的小细节部分。这可能是最简单的方法。

控制

$scope.select = function(item) {
  $scope.selected = item;
}
$scope.selected = {};

HTML

<a class="list-group-item" ng-click="select(item)" ng-repeat="item in itemDetails">
  {{item.name}}
</a>

然后selected对象可以这样使用:

<h2>Name: {{selected.name}}</h2>
etc...

请参阅我的示例:http://plnkr.co/edit/mUMZ0VGO8l1ufV1JJNQE?p=preview