0

I need to enable/disable a button after click with Angular. When a user clicks "Submit form", it makes an http request. If an error occurs (inside the catch), I want to re-enable the directive button so that a user can try again. I have a directive with controllerAs syntax and isolateScope. Below is the code I have (simplified for here);

myCtrl parent controller (controllerAs is myCtrl)

    vm.submit = function() {
      MyService
        .update()
        .then(function(res) {
          // success
        })
        .catch(function(err) {
          vm.error = true;
          // error
        });
    };

Parent view with my-form directive

<my-form form-submit='myCtrl.submit()'></my-form>

myForm Directive

  function myForm() {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: 'myform.html',
      scope: {
        formSubmit: '&',
      },
      require: ['form', 'myForm'],
      link: function(scope, element, attrs, ctrls) {
        var formCtrl = ctrls[0];
        var directiveCtrl = ctrls[1];

        scope.isButtonDisabled = false;

        scope.submit = function() {
          scope.submitted = true;
          directiveCtrl.submit();
        };
      },
      controller: function($scope, $element, $attrs) {
        var vm = this;

        // Submit parent function
        vm.submit = function() {
          vm.formSubmit();
        };
      },
      controllerAs: 'myFormCtrl',
      bindToController: true
    };
  }

  angular.module('mymodule')
    .directive('myForm', [ myForm ]);

myForm directive template

<form name='myForm' novalidate>
    // form fields
    <button ng-click='submit()' ng-disabled='isButtonDisabled'>Submit Form</button>
</form>

1 Answer 1

0

Instead of having the promise resolved in the parent controller, you could just pass the promise back to the child controller and handle the logic there. Something like this should work:

parent:

vm.submit = function() {
  return MyService.update().$promise;
};

child:

vm.submit = function() {
      vm.formSubmit().then(function(res) {
      // success
    })
    .catch(function(err) {
      vm.error = true;
      // error
      scope.isButtonDisabled = false;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.