简体   繁体   English

如何使用AngularJS延迟启用按钮?

[英]How do I enable a button after a delay using AngularJS?

I am using the ng-disabled directive to control when a button on my page can be clicked. 我正在使用ng-disabled指令来控制何时可以单击页面上的按钮。 Is it possible to control this via a timer? 是否可以通过计时器控制它? I would like the button to be disbaled until 5 seconds have elapsed. 我希望按钮被移除直到5秒钟过去。 My HTML is currently: 我的HTML目前是:

<div ng-controller="ResetController">
    <button ng-click="reset()">Reset</button>
</div>

You can use $timeout : 你可以使用$timeout

$timeout(function() {
   $scope.buttonEnabled = true;
}, 5000);

And in your html: 在你的HTML中:

<button ng-click="reset()" ng-disabled="!buttonEnabled">Reset</button>

Also don't forget to inject $timeout into your controller. 另外,不要忘记在控制器中注入$timeout Like any other angular Service ( $http for example). 像任何其他角度服务(例如$http )。

ng-enabled isn't in core, but ng-disabled evaluates based on either true or false so simply use a timeout to assign true to a variable after a desired amount of time to enable accordingly. ng-enabled不在核心,但ng-disabled基于true或false进行评估,因此只需使用超时在相应的启用时间后为变量赋值true即可。

html: HTML:

<button ng-disabled="isDisabled">click me after 3 seconds</button>

controller: 控制器:

function($scope, $timeout) {
  $scope.isDisabled= true;
  $timeout(function(){
    $scope.isDisabled= false;
  }, 3000)
}

You need to set a variable in your controller, then set ng-disabled using that variable. 您需要在控制器中设置变量,然后使用该变量设置ng-disabled。

For example, assuming a controller ExampleController registered with controller-as "example": 例如,假设一个控制器ExampleController注册了控制器 - 作为“示例”:

(function() {
    'use strict';
    angular.module('app').controller('ExampleController',ExampleController);
    ExampleController.$inject = ['$timeout'];

    function ExampleController($timeout) {
        var vm = this;
        vm.buttonDisabled = true;
        $timeout(function() { 
            vm.buttonDisabled = false;
        }, 5000);
    }
})();

Then in your template: 然后在你的模板中:

<input type="button" ng-disabled="example.buttonDisabled"/>

you need to use timeout as per the previous answer ... 您需要按照之前的答案使用超时...

$scope.buttonDisabled = true;

$timeout(function() {
   $scope.buttonDisabled = false;
}, 5000);

don't forget to inject $timeout into your controller / service. 不要忘记在控制器/服务中注入$ timeout。

then in your HTML do ... 然后在你的HTML中做...

<div ng-controller="ResetController">
    <button ng-click="reset()" ng-disabled="buttonDisabled">Reset</button>
</div>

Try this: 尝试这个:

var interval= setInterval(timePassed, 1000);
function timePassed() {
   $scope.buttonEnabled = true;
}

and: 和:

<input type="button" ng-enabled="buttonEnabled"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM