这是我的index.html的样子:

javascript - AngularJS querySelector通过ID返回未定义-LMLPHP

这是Javascript代码(角度):

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


如您所见,我正在尝试通过搜索等于tile3的ID来查找controllerElement。但是,每当我到达下一行时,程序都会因以下错误而崩溃:


  未捕获的TypeError:无法读取null的属性“ getAttribute”


有什么明显的我想念的吗?

编辑

这是完整的代码,由于某些原因现在未定义controllerScope var ...

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);的行仅打印“ undefined”。

最佳答案

如果使用querySelector,则可以/应该将#tile3用作传递给函数的值,因此:

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

09-30 16:08