使用 angularjs $timeout with "this" insted of $scope
using angularjs $timeout with "this" insted of $scope
我需要使用 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);
}
});
在像 ng-controller="testCtrl as vm"
这样的 html 上声明控制器时,请使用 controllerAs
模式。因此 vm
基本上将具有控制器的别名,它将负责 object
使 this
的值在 HTML 上进行绑定。
标记
<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);
}
});
此外,我还建议您将 this
上下文放在某个变量中,这样您就不会遇到与此相关的问题。参考 了解更多信息
我需要使用 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);
}
});
在像 ng-controller="testCtrl as vm"
这样的 html 上声明控制器时,请使用 controllerAs
模式。因此 vm
基本上将具有控制器的别名,它将负责 object
使 this
的值在 HTML 上进行绑定。
标记
<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);
}
});
此外,我还建议您将 this
上下文放在某个变量中,这样您就不会遇到与此相关的问题。参考