Valentin Garcia Valentin Garcia - 3 days ago 4
AngularJS Question

ng-init with json file

Can I use a json file in ng-init to get data of the json file ?

I have this example but I want to replace my object by the json file.

<html>
<head>
<title></title>
</head>
<body ng-app>
<input type="text" ng-model="query"/>
<div ng-init="users=['coucou', 'ca va']"> <!--to be replaced by data contains in a json file-->
{{users}}
<ul>
<li ng-repeat="user in users">
{{user}}
</li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
</body>
</html>

Answer

HTML

<body ng-app='app'>
  <div ng-init="getData()" ng-controller="listController">
    {{users}}
    <ul>
      <li ng-repeat="user in users">
        {{user}}
      </li>
    </ul>
  </div>
</body>

Controller:

var app = angular.module("app", []);
    app.controller("listController", ["$scope", "$http",
      function($scope, $http) {
        $scope.getData = function() {
          $http.get('test.json').then(function(response) {
            $scope.users = response.data;
          });
        }
      }
    ]);

DEMO

Comments