【发布时间】:2015-06-04 21:12:32
【问题描述】:
我正在使用 Angularjs 进行前端开发。最近我开始实现 Webpack,然后我意识到 angular.element($window).scrollTop() 停止工作并开始抛出错误,因为“windowElement.width 不是函数”。以下是 webpack 的旧代码和新代码。
旧的工作代码:
app.directive("ajnav", ['$window', '$location', function ($window, $location) {
return {
restrict: "E",
templateUrl: "/templates/common/AJNav.html",
replace: true,
scope: {
seo: '=',
conf: '='
},
link: function (scope, element, attrs) {
//Bind event change the postion of AJ Nav on scroll
var windowElement = angular.element($window);
var onScrollHandler = function () {
//Get current height of iNav.
var iNavHeight = $("#iNavNGI_Header").height();
if (windowElement.scrollTop() > iNavHeight) {
$(element).addClass('navbar-fixed-top');
$(element).removeClass('aj-nav-container-absolute');
}
else {
$(element).removeClass('navbar-fixed-top');
$(element).addClass('aj-nav-container-absolute');
}
};
//Bind event handler on scroll
windowElement.on('scroll', scope.$apply.bind(scope, onScrollHandler));
}
};
}]);
使用 webpack 的新代码抛出错误:
var $ = require("jquery");
var angular = require("angular");
var Utilities = require("./../../utilities/Utilities");
var AppUtilities = require("./../../utilities/AppUtilities");
module.exports = ['$window', '$location', function ($window, $location) {
return {
restrict: "E",
templateUrl: "/templates/common/AJNav.html",
replace: true,
scope: {
seo: '=',
conf: '='
},
link: function (scope, element, attrs) {
//Bind event change the postion of AJ Nav on scroll
var windowElement = angular.element($window);
var onScrollHandler = function () {
//Get current height of iNav.
var iNavHeight = $("#iNavNGI_Header").height();
if (windowElement.scrollTop() > iNavHeight) {
$(element).addClass('navbar-fixed-top');
$(element).removeClass('aj-nav-container-absolute');
}
else {
$(element).removeClass('navbar-fixed-top');
$(element).addClass('aj-nav-container-absolute');
}
};
//Bind event handler on scroll
windowElement.on('scroll', scope.$apply.bind(scope, onScrollHandler));
}
};
}];
Follownig 是我得到的异常的堆栈跟踪。
TypeError: windowElement.scrollTop is not a function
at module.exports.link.onScrollHandler (site.min.js:42181)
at Scope.$get.Scope.$eval (ite.min.js:25066)
at Scope.$get.Scope.$apply (site.min.js:25165)
at eventHandler (site.min.js:12594)
我在指向 App.js 的条目中绑定了这个指令,如下所示
app.directive("ajnav", require("./directives/common/AJNav"));
我尝试了所有可以但无法修复的选项。请帮忙。
【问题讨论】:
标签: angularjs angularjs-directive webpack