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.
You can just loop over your names 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With