Questions › Set values to html tag from angularjs controller not working

I want to show the user profile values in HTML via an AngularJs controller, but it isn't showing in the html <p> where I bind them. jsfiddle

AngularJs App:

var app = angular.module('myApp', []);

app.service('UserService', function () {
    var userDetails = [{
            id : 27,
            first_name : 'Addy',
            last_name : 'Villiams',
            gender : 1,
            email : 'addy@villiams.com',
            creation_date : '2015-09-23 10:53:19.423',
            age : 25,
            profile_pic : 'avatar.get?uid=27'
    }];

    this.get = function () {
        return userDetails;
    }
});


app.controller('UserController', function ($scope, UserService) {

    $scope.userinfo = UserService.get();

});

HTML:

<div ng-controller="UserController">
    <p>{{userinfo.id}}</p>
    <p>{{userinfo.first_name}}</p>
</div>
Comments :

You are returning an array from your service var userDetails = [{ try returning just the straight object.... fiddle


4 Answers :
Tushar answered

The returned object from service is an array with one object.

$scope.userinfo = UserService.get()[0]; // Get the first element from array

Demo

Or change the service to return an Object instead of array.

var userDetails = {
    id: 27,
    first_name: 'Addy',
    last_name: 'Villiams',
    gender: 1,
    email: 'addy@villiams.com',
    creation_date: '2015-09-23 10:53:19.423',
    age: 25,
    profile_pic: 'avatar.get?uid=27'
};

Demo

Tushar replied
@PraveenRawat Welcome! :);
Grissom answered

So your service UserService.get() returns array of objects so userinfo.id and userinfo.first_name are undefined. You can resolve it returning just object or using on view userinfo[0].id and userinfo[0].first_name. Please check fiddle http://jsfiddle.net/rawat/k3phygpz/533/

Tushar answered

Remove the [] braces - you should return an object not an array:

var userDetails = {
    id: 27,
    first_name: 'Addy',
    last_name: 'Villiams',
    gender: 1,
    email: 'addy@villiams.com',
    creation_date: '2015-09-23 10:53:19.423',
    age: 25,
    profile_pic: 'avatar.get?uid=27'
};
Tushar answered

You initialized user object in array. You can remove the square brackets [] from user initialization:

var userDetails = {
    id: 27,
    first_name: 'Addy',
    last_name: 'Villiams',
    gender: 1,
    email: 'addy@villiams.com',
    creation_date: '2015-09-23 10:53:19.423',
    age: 25,
    profile_pic: 'avatar.get?uid=27'
};

or use

$scope.userinfo = UserService.get()[0];