使用Angularjs将外部json文件排序到html中的表

时间:2017-03-21 09:16:23

标签: angularjs json

我正在尝试从角度js中的外部文件中对json进行排序。当我在内部将json声明为数组时,我能够轻松地对文件进行排序,但在外部文件中声明json时无法获取数据。请帮助我。 我的代码是:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Angularjs UI-Grid Example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ui-grid.info/release/ui-grid.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
<script type="text/javascript">
var app = angular.module("uigridApp", ["ui.grid"]);
app.controller("uigridCtrl", function ($scope, $http) {
     $http.get("views.json")
     .then(function (response) {$scope['users'] = response.data;console.log(response.data);
                             //$scope['counter'] = Object.keys(response.data).length;

                             });
/*$scope.users = [
{ name: "Madhav Sai", age: 10, location: 'Nagpur' },
{ name: "Suresh Dasari", age: 30, location: 'Chennai' },
{ name: "Rohini Alavala", age: 29, location: 'Chennai' },
{ name: "Praveen Kumar", age: 25, location: 'Bangalore' },
{ name: "Sateesh Chandra", age: 27, location: 'Vizag' }
];*/
});
</script>
<style type="text/css">
.myGrid {
width: 500px;
height: 200px;
}
</style>
</head>
<body ng-app="uigridApp">
<h2>AngularJS UI Grid Example</h2>
<div ng-controller="uigridCtrl">
<div ui-grid="{ data: users }" class="myGrid"></div>
</div>
</body>
</html>

和views.json包含

[  
   {  
      name:"Madhav Sai",
      age:10,
      location:"Nagpur"
   },
   {  
      name:"Suresh Dasari",
      age:30,
      location:"Chennai"
   },
   {  
      name:"Rohini Alavala",
      age:29,
      location:"Chennai"
   },
   {  
      name:"Praveen Kumar",
      age:25,
      location: "Bangalore"
   },
   {  
      name:"Sateesh Chandra",
      age:27,
      location:"Vizag"
   }
] 

请帮帮我。

1 个答案:

答案 0 :(得分:1)

你可以这样做,

app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
  $scope.gridOptions = {
    columnDefs: [
      { field: 'name' },
      { field: 'age' },
      { field: 'location' }
    ]
  };

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

<强> DEMO