[英]AngularJS querySelector by ID Returns Undefined
Here is what my index.html looks like: 这是我的index.html的样子:
And this is the Javascript code (angular): 这是Javascript代码(角度):
var controllerElement = document.querySelector('[id="tile3"]');
console.log(controllerElement.getAttribute('class'));
var controllerScope = angular.element(controllerElement).scope();
As you can see, I'm trying to find the controllerElement by searching for an id equal to tile3
. 如您所见,我正在尝试通过搜索等于
tile3
的id来tile3
。 However, whenever I get to the next line the program crashes with this error: 但是,每当我到达下一行时,程序都会因以下错误而崩溃:
Uncaught TypeError: Cannot read property 'getAttribute' of null
未捕获的TypeError:无法读取null的属性“ getAttribute”
Is there something obvious I'm missing? 有什么明显的我想念的东西吗?
EDIT 编辑
Here is the full code, now the controllerScope
var is being undefined for some reason... 这是完整的代码,由于某些原因现在未定义
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"});
})();
The line where it says console.log(controllerScope);
该行显示
console.log(controllerScope);
is just printing "undefined". 只是打印“未定义”。
如果使用querySelector,则可以/应该将#tile3用作传递给函数的值,因此:
var tile3 = document.querySelector('#tile3')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.