2015-11-09 69 views
0

這裏是我的index.html的樣子:AngularJS querySelector通過ID返回undefined

enter image description here

這是Javascript代碼(角):

var controllerElement = document.querySelector('[id="tile3"]'); 
console.log(controllerElement.getAttribute('class')); 
var controllerScope = angular.element(controllerElement).scope(); 

正如你所看到的,我試圖通過搜索一個等於tile3的ID來找到controllerElement。然而,每當我到達下一行程序崩潰與此錯誤:

Uncaught TypeError: Cannot read property 'getAttribute' of null

是否有什麼明顯的我失蹤?

編輯

下面是完整的代碼,現在controllerScope變種正在未定義出於某種原因...

var update = function(id, channel){ 
    var controllerElement = document.querySelector('#tile3'); 
    console.log(controllerElement.getAttribute('ng-controller')); 
    var controllerScope = angular.element(controllerElement).scope(); 
    console.log(controllerScope); 
    controllerScope.$apply(function() { 
     controllerScope[id].username = channel.username; 
     controllerScope[id].keyword = channel.keyword; 
     controllerScope[id].percent = channel.percent; 
     controllerScope[id].views = channel.views; 
     controllerScope[id].link = channel.link; 
    }); 
}; 

(function(){ 
    var app = angular.module("testApp", []); 

    var TileController = function($scope){ 
     $scope.channels = []; 
     for(i = 0; i < 25; i++){ 
      var channel = { 
       username:"John", 
       keyword:"Doe", 
       percent:"50%", 
       views:5000, 
       link:"http://www.twitch.tv/lolyou" 
      }; 
      $scope.channels.push(channel); 
     } 

    }; 

    app.controller("TileController", ["$scope", TileController]); 

    update(3, {username:"Yo", 
       keyword:"Bro", 
       percent:"40%", 
       views:35, 
       link:"http://www.twitch.tv/nickbunyun"}); 
})(); 

在那裏說:console.log(controllerScope);線只是打印「未定義」。

+0

這哪裏是代碼queryselector? –

+0

你在說什麼?它表示document.querySelector(...)的那一行;?錯誤正在被拋出第二行。 –

+0

是的,它是在控制器或什麼的 –

回答

1

如果您正在使用querySelector那麼你可以/應該只使用#tile3作爲傳遞給函數的值,所以:

var tile3 = document.querySelector('#tile3')

+0

var controllerElement = document.querySelector('#tile3');該代碼仍會拋出相同的錯誤。 –

+2

我相信你需要發佈你寫的全部JavaScript代碼。看起來div並不是在你嘗試獲取它時創建的,因此它是空的。 –

+0

awww,我的腳本創建在我的索引文件的頭部,所以它被稱爲身體被創建之前我猜。我只是將腳本標記移到了主體的底部,但是我收到了一個新錯誤:「Uncaught TypeError:無法讀取屬性$ apply'undefined」,考慮到它成功地打印出元素的類屬性,這很奇怪這意味着元素被定義。 –