3

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 : '[email protected]',
            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>
1
  • 1
    You are returning an array from your service var userDetails = [{ try returning just the straight object.... fiddle Commented Oct 5, 2015 at 7:22

4 Answers 4

4

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: '[email protected]',
    creation_date: '2015-09-23 10:53:19.423',
    age: 25,
    profile_pic: 'avatar.get?uid=27'
};

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

@PraveenRawat Welcome! :)
1

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/

Comments

1

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

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

Comments

1

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: '[email protected]',
    creation_date: '2015-09-23 10:53:19.423',
    age: 25,
    profile_pic: 'avatar.get?uid=27'
};

or use

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

Comments

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.