Reputation: 25122
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
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();
});
Upvotes: 2
Views: 2316
Reputation: 25159
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();
});
Upvotes: 2