AngularJS querySelector by ID返回Undefined

时间:2015-11-09 01:15:34

标签: javascript angularjs

这是我的index.html的样子:

enter image description here

这是Javascript代码(angular):

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);的行只是打印“未定义”。

1 个答案:

答案 0 :(得分:1)

如果你正在使用 querySelector 那么你可以/应该只使用#tile3作为传递给函数的值,所以:

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