Pavan S Pavan S - 3 months ago 12
AngularJS Question

Print the JSON in angular js, I can see in console. but cant able to print the same

I am missing something very simple. Please help me out.

In my controller i am getting the JSON object.

app.controller("dashboardCtrl", ["$scope","authFactory","$location",function($scope,authFactory,$location){

var userObj = authFactory.getUserObj(userObj);
console.log(userObj);
$scope.userObj = userObj;

var accessToken = authFactory.getAccessToken();
console.log(accessToken);
$scope.accessToken = accessToken;

$scope.FBout = function(){

FB.logout(function(response) {
authFactory.clearCookie();
$location.path("/");
$scope.$apply();
});


};
}]);


in the console. i get the response as follows

{"name":"Pavan Sudheendra","id":"539193599614696"}


the factory code for the same is as shown below:
app.factory("authFactory",["$cookies","$location",function($cookies,$location){
var authFactory = {};

authFactory.setAccessToken = function(accessToken){
$cookies.put("accessToken",accessToken);
}

authFactory.getAccessToken = function(){
return $cookies.get("accessToken");
}

authFactory.getUserObj = function(){
var userObj = $cookies.get('userObj');

if(userObj){
return userObj;
}
else {
console.log("error");
}
}

authFactory.clearCookie = function(){

$cookies.remove("accessToken");
$cookies.remove("userObj");

}

authFactory.isAuthenticated = function(){
var isLoggedIn=$cookies.get("accessToken")?true:false;
return isLoggedIn;
}
return authFactory;
}]);


but i am trying to use that object. to print it in the front end. like

this is dashboard {{accessToken}} {{userObj.name}}



I am sure i have included every controller and linked the factory to it.. and the thing is..
i am able to print the accesstoken.. but i cant print the name and id of it.

if i try to print {{userObj}}, whole object will be printed. then if i try {{userObj.name}} then i should get the name value of that user object right.

please help me out in figuring this problem out.

Answer

As discussed in the comments, your cookie stores a string, not an object. You can get an object back from your JSON string using the angular.fromJson method.

$scope.userObj = angular.fromJson(userObj)