Search code examples
angularjsng-messagesangularjs-ng-disabled

Is it possible to disable a button in angular js when there are any custom ng-message errors present in the form?


Is is possible to disable a button in a form, when there is any error message in the form other than built in errors such as 'required', 'min-length', such as validating a condition?


Solution

  • Hope the following helps

    1. If you are setting custom errors using $scope.formName.$setValidity('errName', false);, then you can use formName.$error.errName as a condition in ng-disabled

    In JS,

    $scope.formName.$setValidity('errName', false);//invalidate the form
    

    You can set the error to true when needed.

    In HTML,

    <button type="button" ng-disabled="formName.$error.err">Button</button>
    
    1. You can use a flag and toggle it to true when error and use that flag in ng-disabled

    In JS,

    $scope.disableBtn = true; //whenever button is to be disabled.
    

    In HTML,

    <button type="button" ng-disabled="disableBtn">Button</button>

    UPDATE: Adding plunker link https://plnkr.co/edit/5CFpFMAnZ8kkBh5z5vH4?p=preview