How to ascribe a variable to 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 controller:
var name = names.name;
And then I tried in HTML ng-repeat {{name}} but it didn't work.
secondCtrl: promise.then(...) was the good way. But anywhere outside the callback passed tothen()would be useless because service didn't finish retrieving the data