Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ascribe a variable to JSON Angular

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.

like image 986
bafix2203 Avatar asked Dec 23 '16 11:12

bafix2203


Video Answer


1 Answers

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>
like image 50
Mistalis Avatar answered Sep 18 '22 13:09

Mistalis