2013-10-31 34 views
2

剛開始使用AngularJS。嘗試構建一個頁面應用程序,以一次一個地顯示我的漫畫幻燈片/頁面。解析對象時AngularJS插值錯誤

數據從JSON文件中拉出來,並且正常工作。但是當我嘗試設置一些基本綁定時,Angular會拋出錯誤。有什麼想法嗎..?

HTML

<span ng-bind-html="showCurrentTitle"></span> 

JS

錯誤

TypeError: Object function() { return $scope.comics[0].title; } has no method 'indexOf' 

如果我去掉ngSanitize模塊,那麼錯誤信息會改變。

Alt鍵錯誤

Error: [$sce:unsafe] http://errors.angularjs.org/undefined/$sce/unsafe 

如果我換出了老式的鬍子括號中的NG-綁定HTML的指令,那麼錯誤信息再次改變。

Alt鍵的錯誤(2)

Error: [$interpolate:interr] http://errors.angularjs.org/undefined/$interpolate/interr?p0=%7B%7BshowCurr…()%7D%7D&p1=TypeError%3A%20Cannot%20read%20property%20'0'%20of%20undefined 

幫助,好嗎?

乾杯, 丹

+1

建議您在jsfiddle.net中創建一個簡單演示或重現問題的重新啓動。是'title' html嗎?或只是一個字符串? – charlietfl

+0

我應該提及「return $ scope.comics [0] .title;」在使用鬍鬚符號時將正確的值返回到頁面 - 即使它正在引發插值錯誤... 當我使用ngBindHtml時,返回值完全丟失。 – Dan

+0

謝謝Charlietfl,我會給你一個破解。我早些時候嘗試過,但趕上使JSON工作。可能加載一個虛擬對象... – Dan

回答

1

我不熟悉您收到錯誤,或NG-的sanitize或NG綁定 - html標記。但是,您的JavaScript代碼看起來有問題。

var comicsApp = angular.module('comicsApp', ['ngSanitize']); 

    comicsApp.controller('comicsCtrl', ['$scope', '$http', 
     function comicsCtrl($scope, $http) { 

     //so this runs immediately, but . . . 
     $http.get('/luv-slimline/test/comics.json').success(function(data) { 
      // . . . this is going to happen async, so this value won't be set 
      //before the initial binding occurs 
      $scope.comics = data.comics; 
     }); 
    $scope.showCurrentTitle = function() { 
    // . . . as a result, comics will be undefined initially. 
    return $scope.comics[0].title; 
} 
} //end ComicsCtrl 
]); 

我認爲你需要之前你http.get爲$ scope.comics 定義的初始值。喜歡的東西:

$scope.comics = []; 
$scope.comics.push({title: "testTitle"}); 

編輯

基於您的評論,如果你現在只是結合showCurrentTitle(我將重新命名爲currentTitle,因爲它更有意義),你甚至不需要初始化$ scope.comics - 它應該沒有這個代碼。

+0

感謝菲爾,它非常簡單。乾杯! – Dan

+0

菲爾的回答已經擺脫了錯誤,但現在看起來我有一個後續問題。 使用鬍鬚符號,「return $ scope.comics [0] .title」被注入HTML頁面。 使用ng-bind-html,它沒有。 有什麼想法? – Dan

+0

再一次,我不熟悉ng-bind-html,但是如果你想做一個「常規」綁定(使用大括號),不要讓showCurrentTitle成爲一個函數,只需將它設置爲一個值:$ scope.showCurrentTitle = $ scope.comics [0] .title; –