2

After reading this posts: parse json data in angular controller

Here is my problem

I have a controller like this

(function() {
  var SomeController = function($scope, someService, $log, $routeParams, ShareData) {
    var colors = function(data) {
      $scope.Colors = data;
      $scope.result = angular.fromJson(data);
      alert($scope.result);

    };

    var errorDetails = function(serviceResp) {
      $scope.Error = "No connection to server";
    };
    someService.colors().then(colors, errorDetails);

  };

  app.controller("SomeController", ["$scope", "someService", "$log", "$routeParams", "ShareData", SomeController]);

}());

This alert returns [object Object],[object Object] When I try to parse one property of this object it returns undefined.

Here is the code.

(function() {
  var SomeController = function($scope, someService, $log, $routeParams, ShareData) {
    var colors = function(data) {
      $scope.Colors = data;
      //here it returns undefined
      $scope.result = angular.fromJson(data);
      alert($scope.result[0].path);

    };

    var errorDetails = function(serviceResp) {
      $scope.Error = "No connection to server";
    };
    someService.colors().then(colors, errorDetails);

  };

  app.controller("SomeController", ["$scope", "someService", "$log", "$routeParams", "ShareData", SomeController]);

}());

The service is OK and it returns two complex objects which have a property named path.

1
  • What do you want $scope.result to look like? Array of paths or something else? Commented Jun 16, 2015 at 18:53

2 Answers 2

2

Alert returns [object Object],[object Object] - it means that data is array of objects. So you don't have to parse anything to get data, it's already parsed.

For example, you can access path of the first object in array or construct array of paths:

var colors = function(data) {
  $scope.Colors = data;

  // path from the first object in array
  $scope.result0 = data[0].path;

  // array of paths
  $scope.result = data.map(function(obj) {
     return obj.path;
  });
};
Sign up to request clarification or add additional context in comments.

2 Comments

$scope.result0 = data[0].path; is still returning undefined.
Awesome. got it. P was upper case in property.
0

You're not not being very descriptive with your question.

Here's a tip...

Set a breakpoint where the [object Object] is appearing and checkout what your getting.

1 Comment

Sorry I can't vote you up. The system doesn't allow me.

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.