尝试 angularjs 指令,但没有真正起作用
Trying out an angularjs directive, not really working
所以我正在尝试使用一个指令,我在 Internet 上找到的所有内容看起来都与我得到的完全一样。
这是我做的指令:
angular.module('App');
App.directive("scrollBottom", ["$interval", function ($interval) {
return {
restrict: "A",
link: function (scope, elem, attrs) {
$('a').click(function () {
$('html, body').animate({
scrollTop: $($(this).attr('#myAnchor')).offset().top
}, 40000);
return false;
});
}
}
}]);
这就是我想要调用指令的方式:
<button scrollBottom>Click me!</button>
但可悲的是它甚至不起作用。
你们看到问题了吗?因为我在控制台中没有收到任何错误。
您需要将驼峰式拆分为破折号,如下所示:
<button scroll-bottom>Click me!</button>
您在控制台中看不到任何错误,因为它只是一个没有任何意义的普通属性。
除此之外你不应该通过
调用你的指令
<button scrollBottom>Click me!</button>
但是
<button scroll-bottom>Click me!</button>
你还必须检查,在控制台中应该是一个异常,比如 App 模块不可用,这是因为你必须从
更改指令创建
angular.module('App');
App.directive
进入
var app = angular.module('App');
app.directive
你做错了。您正在将此点击处理程序添加到页面上的每个 "a" 元素。您只需将此事件添加到您的指令中。你可以达到
var app = angular.module('App');
app.directive("scrollBottom", [function () {
return {
restrict: "A",
link: function (scope, elem, attrs) {
$(elem).click(function () {
$("html, body").animate({
scrollTop: 0
});
return false;
});
}
}
}]);
顺便说一句,您在 html 上错误地使用了指令。指令名称上的驼峰式大小写转换为 html 上的驼峰式大小写。
所以你需要使用你的指令 as
scroll-bottom
编辑:我简化了 scrollTop 代码
所以我正在尝试使用一个指令,我在 Internet 上找到的所有内容看起来都与我得到的完全一样。
这是我做的指令:
angular.module('App');
App.directive("scrollBottom", ["$interval", function ($interval) {
return {
restrict: "A",
link: function (scope, elem, attrs) {
$('a').click(function () {
$('html, body').animate({
scrollTop: $($(this).attr('#myAnchor')).offset().top
}, 40000);
return false;
});
}
}
}]);
这就是我想要调用指令的方式:
<button scrollBottom>Click me!</button>
但可悲的是它甚至不起作用。 你们看到问题了吗?因为我在控制台中没有收到任何错误。
您需要将驼峰式拆分为破折号,如下所示:
<button scroll-bottom>Click me!</button>
您在控制台中看不到任何错误,因为它只是一个没有任何意义的普通属性。
除此之外你不应该通过
调用你的指令<button scrollBottom>Click me!</button>
但是
<button scroll-bottom>Click me!</button>
你还必须检查,在控制台中应该是一个异常,比如 App 模块不可用,这是因为你必须从
更改指令创建angular.module('App');
App.directive
进入
var app = angular.module('App');
app.directive
你做错了。您正在将此点击处理程序添加到页面上的每个 "a" 元素。您只需将此事件添加到您的指令中。你可以达到
var app = angular.module('App');
app.directive("scrollBottom", [function () {
return {
restrict: "A",
link: function (scope, elem, attrs) {
$(elem).click(function () {
$("html, body").animate({
scrollTop: 0
});
return false;
});
}
}
}]);
顺便说一句,您在 html 上错误地使用了指令。指令名称上的驼峰式大小写转换为 html 上的驼峰式大小写。 所以你需要使用你的指令 as
scroll-bottom
编辑:我简化了 scrollTop 代码