什么是实现一个按钮,需要被禁用,而在AngularJS提交的最佳方式? [英] What is the best way to implement a button that needs to be disabled while submitting in AngularJS?

查看:86
本文介绍了什么是实现一个按钮,需要被禁用,而在AngularJS提交的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个提交按钮的表单,表单将需要10秒回来,我不希望用户在表单上点击同时。我的方法迄今已在按钮上的文字被设置为 buttonText =载入中...,并使用 NG-禁用同当我这样做,我设置的提交( isSubmitted )的标志。考虑到这一定是一种普遍现象,什么是这样做的最好的,最可重用的方式?

I have a form with a submit button, the form will take 10 seconds to come back and I don't want the user to be clicking on the form meanwhile. My approach so far has been setting the text of the button to buttonText="Loading..." and using ng-disable with a flag that I'm setting when I do the submit(isSubmitted). Considering this must be a general pattern, what is the best and most reusable way of doing this?

推荐答案

创建一个自定义指令可重复使用的组件。该指令应该创建一个分离的范围,并使用'和;'语法指定按钮被点击时要调用哪个父作用域的功能。传递一个回调函数,所以在任务完成时,该指令可以撤消按钮标签变化和残疾人属性。

Create a reusable component with a custom directive. The directive should create an isolate scope and use the '&' syntax to specify which parent scope function to call when the button is clicked. Pass a callback function so the directive can undo the button label change and the disabled attribute when the task is completed.

HTML

<button wait-button do-stuff="doStuff(cbFn)">button label</button>

指令:

myApp.directive('waitButton', function() {
    return {
        scope: {
            doStuff: '&'
        },
        link: function(scope, element) {
            var normalText = element.text();
            var callbackFn = function() {
                console.log('callback')
                // element[0] is the (unwrapped) DOM element
                element[0].disabled = false;
                element.text(normalText);
            }
            element.bind('click', function() {
                element[0].disabled = true;
                element.text('Loading...');
                // Weird syntax below!  Arguments must 
                // be passed inside an object:
                scope.doStuff({cbFn: callbackFn});
            })
        }
    }
})

function MyCtrl($scope, $timeout) {
    $scope.doStuff = function(callbackFn) {
        console.log('doStuff');
        // Do stuff here... then call the callback.
        // We'll simulate doing something with a timeout.
        $timeout(function() {
            callbackFn()
        }, 2000)
    }
}

小提琴

这篇关于什么是实现一个按钮,需要被禁用,而在AngularJS提交的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆