[英]Angular: can't access a variable inside an element.bind in my angular directive so I can manipulate the DOM with it
我正在嘗試編寫一條指令,該指令返回一個布爾值,該布爾值在用戶在特定容器上滾動時為true,在用戶不滾動時為false。 我這樣做的原因是,當我將console.log放入所使用的element.bind('scroll')時,可以看到Boolean正確切換,但是它不會影響我在之外設置的同名作用域變量element.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
更新: 小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.