无法访问我的Javascript对象的属性

时间:2013-05-02 15:22:01

标签: javascript angularjs

我正在使用Angular.js从我的API中获取单个记录。我将记录作为对象返回,我可以记录对象并查看它的属性,但我无法访问任何属性。我得到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);

更新

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

1 个答案:

答案 0 :(得分: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();
});