2013-05-02 136 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