[英]Angular: can't access a variable inside an element.bind in my angular directive so I can manipulate the DOM with it
I'm trying to write a directive that returns a boolean that is true when the user is scrolling on a specific container, and false when they are not scrolling. 我正在尝试编写一条指令,该指令返回一个布尔值,该布尔值在用户在特定容器上滚动时为true,在用户不滚动时为false。 I have this working in that I can see Boolean toggling properly when I throw a console.log inside the element.bind('scroll') I'm using, but it's not affecting the scope variable of the same name I set outside of the element.bind.
我这样做的原因是,当我将console.log放入所使用的element.bind('scroll')时,可以看到Boolean正确切换,但是它不会影响我在之外设置的同名作用域变量element.bind。 You can see this happening if you take a look at this JSFiddle I threw together: https://jsfiddle.net/hurgledurf/bwyyL7mj/
如果您看一下我聚在一起的这个JSFiddle,就可以看到这种情况: https ://jsfiddle.net/hurgledurf/bwyyL7mj/
This is the code I have for the directive: 这是指令的代码:
(function() {
'use strict';
angular
.module('myWebPage')
.directive('scrollingDirective', scrollingDirective);
function scrollingDirective() {
var directive = {
restrict: 'AE',
link: link
};
return directive;
function link (scope, element, attributes) {
scope.actuallyScrolling = true;
var timer;
element.bind('scroll', function () {
scope.actuallyScrolling = true;
console.log('USER IS SCROLLING ', scope.actuallyScrolling);
clearTimeout(timer);
setTimeout(function () {
scope.actuallyScrolling = false;
console.log('INSIDE TIMER ', scope.actuallyScrolling);
}, 1000);
})
}
}
})();
And this is some basic HTML I threw together as an example: 这是一些我以示例的基本HTML格式:
<body ng-app="myWebPage">
<div class="container" scrolling-directive>
<p>
scroll and check the console.log!
Scrolling Boolean: {{actuallyScrolling}}
</p>
<div class="filler"></div>
</div>
</body>
If you take a look at the JS Fiddle, you can see that the scope.actuallyScrolling variable toggles on and off in the console.log, but doesn't change on the DOM. 如果您看一下JS Fiddle,您会发现scope.actuallyScrolling变量在console.log中打开和关闭,但在DOM上没有变化。 This makes me thing that there's some sort of scoping issue going on that I haven't figured out, and Angular is treating them as two separate variables.
这让我觉得有一个范围界定问题正在发生,但我还没有弄清楚,Angular将它们视为两个单独的变量。 Anyone have any insight into this?
有人对此有任何见识吗? Thank you.
谢谢。
您可以使用scope.$apply()
手动初始化scope
更新: 小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.