我正在尝试编写一个指令,该指令返回一个 bool 值,当用户在特定容器上滚动时返回 true,当用户不滚动时返回 false。我有这个工作,当我在我正在使用的 element.bind('scroll') 中抛出 console.log 时,我可以正确地看到 bool 切换,但它不会影响我在外部设置的同名范围变量元素.绑定(bind)。如果你看一下我整理的这个 JSFiddle,你就会看到这种情况的发生: https://jsfiddle.net/hurgledurf/bwyyL7mj/
这是我的指令代码:
(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);
})
}
}
})();
这是我整理的一些基本 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>
如果您查看 JS Fiddle,您可以看到scope.actuallyScrolling 变量在console.log 中打开和关闭,但在DOM 上没有更改。这让我觉得存在某种我还没有弄清楚的范围问题,而 Angular 将它们视为两个单独的变量。有人对此有任何见解吗?谢谢。
最佳答案
您可以使用scope.$apply()
手动初始化scope
更新:fiddle
关于javascript - Angular : can't access a variable inside an element. 绑定(bind)在我的 Angular 指令中,这样我就可以用它来操作 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45830730/