這裏是我的index.html的樣子:AngularJS querySelector通過ID返回undefined
這是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);
線只是打印「未定義」。
這哪裏是代碼queryselector? –
你在說什麼?它表示document.querySelector(...)的那一行;?錯誤正在被拋出第二行。 –
是的,它是在控制器或什麼的 –