Assign Angular JSON variable

How to write a variable in JSON name ?

JSON names object

 [ { "name": "John", "age" : "12" }, { "name": "Ben", "age" : "15" }, { "name": "Jason", "age" : "18" }, { "name": "Billy", "age" : "11" } ] 

Angular service and controller

 var app = angular.module('app', []); app.service('service', function($http, $q){ var deferred = $q.defer(); $http.get("jsonfile.json").then(function(data){ deferred.resolve(data); }); this.getNames = function(){ return deferred.promise; } }); app.controller('secondCtrl', function($scope, service){ var promise = service.getNames(); promise.then(function(data){ $scope.names = data.data; console.log($scope.names); }); }); 

What I tried to do in the controller:

 var name = names.name; 

And then I tried ng-repeat {{name}} in HTML, but that didn't work.

+6
source share
1 answer

You can simply iterate over the name object in HTML with ng-repeat .

If your array is:

 $scope.names = [ { "name": "John", "age" : "12" }, { "name": "Ben", "age" : "15" }, { "name": "Jason", "age" : "18" }, { "name": "Billy", "age" : "11" } ]; 

You can show names.name with this code:

 <div ng-repeat="n in names">{{n.name}}</div> 
+3
source

Source: https://habr.com/ru/post/1013463/


All Articles