通过NG点击(JS)加载JSON数据

时间:2015-04-18 20:01:42

标签: javascript json angularjs ng-repeat

我在使用NG CLICK加载一组JSON数据时遇到问题。没有clickButton函数,数据加载正常。我的JSON数据是否正确结构化?这是我的小提琴。点击[此处](http://jsfiddle.net/al321/08rjqv4k/3/“鼠标悬停在”)

    $scope.items = [
    {
    "Name":"Sam",

    "Address":"Street",

    "Phone":"111",

    "status":"Available"

    }, 

    {
    "Name":"Tom",

    "Address":"Road",

    "Phone":"222",

    "status":"Busy"

    },]

   --js
   var app = angular.module('myApp', []);

    app.controller('myController', 
   ['$scope', '$http', function($scope, $http) {

   $scope.clickButton = function() {
   $http.get('data.json').success(function(data) {
    $scope.items = data.items;
  });
  }

   }]);

2 个答案:

答案 0 :(得分:1)

Plunker

JS

var app = angular.module('myApp', []);
app.controller('myController', ['$scope', '$http', function($scope, $http) {
  $scope.clickButton = function() {
    $http.get('data.json').success(function(data) {
        $scope.items = data;
      });
  }

}]);

标记

  <body ng-controller="myController">
     <div ng-app="myApp">
        <div ng-controller="myController">
          <button ng-click='clickButton()'>Load Data</button>
          <ul ng-repeat="item in items">
            <li ng-repeat="(key, val) in item">{{key}}: {{val}}
            </li>
        </ul>
        </div>
    </div>
  </body>

JSON

[
  {
        "Name":"Sam",

        "Address":"Street",

        "Phone":"111",

        "status":"Available"

    }, 

    {
        "Name":"Tom",

        "Address":"Road",

        "Phone":"222",

        "status":"Busy"

    }
]

答案 1 :(得分:0)

这是你想要完成的吗?

只需用你的ajax调用替换clickButton()函数的内容。

您忘了将()放在ng-click="clickButton()上。你需要实际调用该函数。

Plunker

要添加评论中提到的搜索功能,只需向第一个ng-repeat添加过滤器:

ng-repeat="item in items| filter: {Name: search}"

Plunker with search