2

I am trying to sort json from an external file in angular js.I am able to sort the file easily when i declared json internally as an array but cant able get data when declared json in external file.Please help me. My code is:

<!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>

and views.json contains

[  
   {  
      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"
   }
] 

Please help me.

Harry
  • 323
  • 1
  • 6
  • 12
  • Possible the same answered questions here http://stackoverflow.com/questions/14478106/angularjs-sorting-by-property – imprezzeb Mar 21 '17 at 09:23
  • No It will not help since i am unable to get json from external file instead of directly defining json array to scope.by commenting my Http.get() method and uncomenting $scope.users it is working fine.but not working when i try to get views.json which is external.But thanks for trying to help me. – Harry Mar 21 '17 at 09:28

1 Answers1

1

You can do this,

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

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396