gpt4 book ai didi

javascript - Angularjs 变量不会改变

转载 作者:行者123 更新时间:2023-11-30 21:13:16 25 4
gpt4 key购买 nike

在控制台中我们看到它发生了变化? http://jsfiddle.net/LCZfd/1006/

app.controller("myCtrl", function($document) {
let scope=this;
this.current=0;

this.isCurrent=function(val){
return val==this.current;
}
this.selectCurrent=function(val){
this.current=val;
}
$document.on('keypress', keyupHandler);
function keyupHandler(keyEvent) {
scope.selectCurrent(keyEvent.key-1);
console.log(scope.current);
}
});

打开控制台,你会看到变量改变了它的值。我只想在我的应用中使用键盘。

最佳答案

这很简单,但我忘记了。如果您使用 Angular 刷新周期外部的事件,则不会应用。这将像这样工作,但不推荐这样做,因为如果您尝试在消化周期中应用,这将导致错误。您应该阅读文档以找到一个解决方案来保持 Angular 边界:

app.controller("myCtrl", function($document, $rootScope) {
let scope=this;
this.current=0;

this.isCurrent=function(val){
return val==this.current;
}
this.selectCurrent=function(val){
this.current=val;
}
$document.on('keypress', keyupHandler);
function keyupHandler(keyEvent) {
//the apply:
$rootScope.$apply(scope.selectCurrent(keyEvent.key-1));
console.log(scope.current);
}
});

关于javascript - Angularjs 变量不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45922007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com