Skip to content Skip to sidebar Skip to footer

What Is The Best Way To Implement A Button That Needs To Be Disabled While Submitting In AngularJS?

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 t

Solution 1:

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>

Directive:

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)
    }
}

Fiddle


Solution 2:

I recommend using jQuery .delegate function: remember "#" = control id and "."= css class

    $("#create").click(function(){
        $('body').append($('<div id="test" class="btn">click me<div>'));
    });

    //-- if you create single button use this
    $("body").delegate("#test", "click", function() {
       alert("worked!"); 
     });

    //-- if you create many buttons use this
    // $("body").delegate(".btn", "click", function() {
      // alert("worked!"); 
    // });

Post a Comment for "What Is The Best Way To Implement A Button That Needs To Be Disabled While Submitting In AngularJS?"