gpt4 book ai didi

javascript - 使用 angularjs $timeout "this"insted of $scope

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

我需要使用 angular $timeout 来显示元素 2 秒。它适用于 $scope 但我现在不知道如何将它与“this”关键字和“controller as ...”语法一起使用。

https://plnkr.co/edit/GPWRg4acYVrP1Ry00D7z?p=preview

angular.module("test", [])
.controller("testCtrl", function($scope, $timeout){

$scope.boo = false;

$scope.disappear = function(){
$scope.boo = true;
$timeout(function () {
$scope.boo = false;
}, 2000);
}
});

最佳答案

在通过 html 声明 Controller 时,请务必使用 controllerAs 模式,如 ng-controller="testCtrl as vm"。因此 vm 基本上将具有 Controller 的别名,它将负责 object 通过 HTML 生成 this 上下文的值以进行绑定(bind)。

标记

<body ng-controller="testCtrl as vm">
<div>
<button ng-click="vm.disappear()">button</button>
<h1 ng-show="vm.boo">Hello Plunker!</h1>
</div>
</body>

代码

angular.module("test", [])
.controller("testCtrl", function($timeout) {
var vm = this;
vm.boo = false;

vm.disappear = function() {
vm.boo = true;
$timeout(function() {
vm.boo = false;
}, 2000);
}
});

Demo Plunkr

此外,我还建议您将 this 上下文放在某个变量中,这样您就不会遇到与 this 相关的问题。引用this answer了解更多信息

关于javascript - 使用 angularjs $timeout "this"insted of $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35661804/

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