Vincent Cueto
Vincent Cueto

Reputation: 225

AngularJS read data from JSON

hello I am new on angular and i come again to have some help. I try to get datas from a json file : teams.json but it doesn't work my controller is like this :

app.controller('TeamController', ['$http', function($http){
    var liste = this;
    liste.teams = [];    
    $http.get('teams.json').success(function(data){
        liste.teams = data;
    });
}]);

and in my html :

<!DOCTYPE html>
<html ng-app="teamStats">

    <head>
        <link rel="stylesheet" href="style.css">
        <script src="script.js"></script>
        <script src="angular.js"></script>
        <script src="app.js"></script>
    </head>
    <body ng-controller="TeamController">
        <!--
        %%%%%%%%%%%%%%%%%%%%%%%%%%% BODY CONTENT        
        -->
        <div id="wrap" >
                <div class="container"> 
                    <div >
                        <ul>
                          <li ng-repeat="team in liste.teams">{{team.name + team.win}}</li>
                        </ul>
                    </div>
                </div> 
        </div>          
        <!--
        %%%%%%%%%%%%%%%%%%%%%%%%%%% END OF BODY CONTENT     
        -->
    </body>
</html>

Many thanks in advance ! hope someone see where i am wrong I did a plunker for easier understanding myPlunker

Best regards, Vincent

Upvotes: 0

Views: 1007

Answers (2)

Vincent Cueto
Vincent Cueto

Reputation: 225

Ok i think i know now why it doesn't work !! ng-repeat, ng-view, ng-include and others use AJAX to load templates. The problem is that the browser by default does not allow AJAX requests to files located on your local file system (for security reasons). Therefore you have two options:

Run local web server that will serve your files Tell your browser to allow local files access

Thanks for help all !! Thanks to Vadim explanation !! And thanks a lot zsong ! :)

Upvotes: 0

zs2020
zs2020

Reputation: 54514

Change your controller to this

  app.controller('TeamController', ['$http', '$scope',
    function($http, $scope) {
      var liste = this;
      $scope.liste = {};
      $scope.liste.teams = [];
      $http.get('teams.json').success(function(data) {
        $scope.liste.teams = data;
      });
    }
  ]);

And fix your json file. You need to remove the additional ,s

Demo: http://plnkr.co/edit/jeHnvykYLwVZLsRLznRI?p=preview

Upvotes: 1

Related Questions