6

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.

2
  • $scope.names = data; console.log($scope.names.name) Commented Dec 23, 2016 at 11:39
  • just like you did in secondCtrl : promise.then(...) was the good way. But anywhere outside the callback passed to then() would be useless because service didn't finish retrieving the data Commented Jan 3, 2017 at 14:12

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Yes i know i can show names.name with ng-repeat="n in names"
Well you said in your original post "And then I tried in HTML ng-repeat {{name}} but it didn't work.". What was that supposed to mean ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.