2

I'm using Angular.js to fetch a single record from my API. I'm getting the record back as an object, I can log the object and see it's properties but I cannot access any of the properties. I just get undefined.

var template = Template.get({id: id});
$scope.template = template;
...
console.log(template); // displays object
console.log(template.content); // undefined

Screenshot of console.log(template);

UPDATE

var id = $routeParams.templateId;
var template = Template.get({id: id});
$scope.template = template;

/*** Template placeholders ***/
$scope.updatePlaceholders = function () {
    var placeholders = [];
    var content = template.content;

    console.log(template); // dumps the object in the screenshot
    console.log("content" in template); // displays false

    // get placeholders that match patter
    var match = content.match(/{([A-z0-9]+)}/gmi);
    ...
}

$scope.$on('$viewContentLoaded', function(){
    $scope.updatePlaceholders();
});
14
  • And what does console.log("content" in template) display? Commented May 2, 2013 at 15:23
  • @MaxArt undefined. He has it there as a comment. Commented May 2, 2013 at 15:24
  • @Yatrix "content" in template and template.content are two totally different things Commented May 2, 2013 at 15:25
  • 2
    Service calls are asynchronous. The return value is not likely to be your expected data until the ajax call returns. Commented May 2, 2013 at 15:25
  • 9
    Chrome shows you the properties of a logged object as they are at expansion time, not as the object existed at log time. At log time, template doesn't have a content property, but by the time you get around to expanding the log entry for inspection, the asynchronous request has completed, and it does have a content property. Commented May 2, 2013 at 15:37

1 Answer 1

2

You need to wait for your HTTP request to complete, then specify what to do in the callback. In this case I've taken it a step further and added a listener to your template object so there's no callback dependency between updatePlaceholders and your resource.

var id = $routeParams.templateId;
var template = Template.get({id: id}, function(res) {
    $scope.template = template;
});

/*** Template placeholders ***/
$scope.updatePlaceholders = function () {
    var placeholders = [];
    var content = $scope.template.content;

    console.log($scope.template); 
    console.log("content" in $scope.template); 

    // get placeholders that match patter
    var match = content.match(/{([A-z0-9]+)}/gmi);
    ...
}

$scope.$watch('template', function(newValue){
    if(newValue) $scope.updatePlaceholders();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for improving this! Works great!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.