joy*_*joy 4 angularjs angularjs-directive webpack
我正在使用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));
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
使用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));
}
};
}];
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
我在我的条目App.js中绑定了这个指令,如下所示
app.directive("ajnav", require("./directives/common/AJNav"));
Run Code Online (Sandbox Code Playgroud)
我尝试了所有可能的选项,但无法修复它.请帮忙.
scrollTop函数是由jquery添加的,你必须在angular之后加载jquery.在这种情况下,您不会将$.fn函数添加到angular.element实例中.你也可以这样做$.fn.scrollTop.call($window).或者$($window).scrollTop()在角度之前加载jquery,以便当前代码按原样运行.
侧注:你不必这样做$(element),元素已经是jq(lite/query)包装,它已经有了add/removeClass可用的功能.
| 归档时间: |
|
| 查看次数: |
14542 次 |
| 最近记录: |