我尝试使用两个params,class和pageYOffset创建一个指令。我想检查元素的滚动位置,如果pageYOffset大于attr中的数字,则添加一个类名。不知怎的,我无法触发班级变化。
HTML
<div scroll offset="1500" ng-class="{active : scrollClass}"></div>
指令
app.directive('scroll', function($window) {
return {
scope: {
offset: "@offset"
},
link: function (scope, element, attr) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= scope.offset) {
scope.scrollClass = true;
}
scope.$apply();
});
}
}
});
答案 0 :(得分:4)
当您使用隔离类时,您的指令范围与控制器范围不同,控制器范围将不会继承到指令范围,因为scope: {..}
,因为您要更改父范围的标记,您需要通过你的指令中带有=
的值,它将执行双向绑定作为内部范围变量更改将影响父范围变量值。
<强> Makrup 强>
<div scroll offset="1500" scroll-class="scrollClass" ng-class="{active : scrollClass}"></div>
<强>指令强>
app.directive('scroll', function($window) {
return {
scope: {
offset: "@offset",
scrollClass: '='
},
link: function (scope, element, attr) {
angular.element($window).bind("scroll", function(event) {
if (element.pageYOffset >= scope.offset) {
//this will change the parent scope variable value to true
scope.scrollClass = true;
}
scope.$apply(); //need full to run digest cycle
});
}
}
});
答案 1 :(得分:0)
你可以试试像tihs:
app.directive('scroll', function($window) {
return {
scope: {
offset: "@offset",
toggleScroll: "&toggle"
},
link: function (scope, element, attr) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= scope.offset) {
toggle();
}
//scope.$apply();
});
}
}
});
<div scroll offset="1500" toggle-scroll="changeActiveClass()" ng-class="{active : scrollClass}"></div>
然后在父范围中定义changeActiveClass:
$scope.changeActiveClass = function() {
$scope.scrollClass = !scrollClass;
}