2013-05-02 103 views
2

我正在使用Angular.js从我的API中获取单个记录。我将记录作为对象返回,我可以记录对象并查看它的属性,但我无法访问任何属性。我刚刚得到undefined无法访问我的Javascript对象的属性

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(); 
}); 
+0

什么'console.log(“模板中的内容”)显示? – MaxArt 2013-05-02 15:23:57

+0

@MaxArt未定义。他在那里作为评论。 – Yatrix 2013-05-02 15:24:44

+0

@Yatrix'“content”in template'和'template.content'是两个完全不同的东西 – Ian 2013-05-02 15:25:23

回答

2

你需要等待你的HTTP请求来完成,然后指定哪些回调做。在这种情况下,我已经更进了一步,并向您的模板对象添加了一个侦听器,以便updatePlaceholders和您的资源之间不存在回调依赖关系。

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(); 
}); 
+0

感谢您改善这一点!很棒! – iamjonesy 2013-05-02 21:17:41