Surya Surya - 1 month ago 6
Javascript Question

I'm new to Angular js, I want to display the local JSON data in the HTML file. Below is the code I tried

I have a sample JSON file

text.json
. I would like to display the data in HTML using
ng-repeat
but it doesn't work.

Here is my code:

<html ng-app="myapp">
<head>
<title> Test</title>
<script src="js/angular.min.js" type="text/javascript"></script>
<script type="text/javascript">
var myapp = angular.module('myapp', []);
myapp.controller('myCtrl', function ($scope, $http) {
$http.get("js/text.json").success(function (response) {
$scope.names = response;
});
});
</script>
</head>
<body>
<div ng-controller="myCtrl">
<li ng-repeat="value in names">
{{value.name +' and the age is ' + value.age}}
</li>
</div>
</body>
</html>


Any suggestions?

Answer

Idea 1

Maybe the JSON file is invalid. Edit it by removing the last comma into this:

[
  {
    "name": "test",
    "age": 28
  },
  {
    "name": "test1",
    "age": 28
  },
  {
    "name": "test2",
    "age": 28
  },
  {
    "name": "test4",
    "age": 28
  },
  {
    "name": "test3",
    "age": 28
  }
]

Idea 2

Double check the path to the JSON file. Is js/text.json really the correct one?

Idea 3

Do you use some web server to display your file in a browser? It probably won't work through a file protocol (e.g. file:///myfile.html), you need a web server and http protocol (e.g. http://localhost:9000).

Idea 4

If you are using some historical version of AngularJS baybe there is a problem with interpolation.

{{}} is a marker for AngularJS interpolation - it means you can display any value which does exist in Angular's scope. You are creating one by ng-repeat. Compared to that, "and the age is" is a simple text which doesn't need an interpolation (it is not variable on Angular's scope but a simple constant).

It means you need to interpolate only {{value.name}} and {{value.age}}. It should work with this code:

<div ng-controller="myCtrl">
   <li ng-repeat="value in names">
      {{value.name}} and the age is {{value.age}}
   </li>
</div>
Comments