Blake Blackwell
Blake Blackwell

Reputation: 7795

Disable jQuery Button with AngularJS and Form Validation

I would like to disable my jQuery button based on form validation. According to the docs this is fairly easy with regular buttons using syntax such as:

 <button ng-click="save(user)" ng-disabled="form.$invalid">Save</button>

However, when changing to a jQuery UI button this no longer works. I assume that Angular has no real binding between jQuery UI and AngularJS and thus would require a directive to do the following:

$("button" ).button( "option", "disabled" );

Is that the case or are there other alternatives? A jsFiddle of what I'm trying to do is here: http://jsfiddle.net/blakewell/vbMnN/.

My code looks like this:

View

<div ng-app ng-controller="MyCtrl">
    <form name="form" novalidate class="my-form">
        Name: <input type="text" ng-model="user.name" required /><br/>
        Email: <input type="text" ng-model="user.email" required/><br/>
        <button ng-click="save(user)" ng-disabled="form.$invalid">Save</button>
    </form>
</div>

Controller

function MyCtrl($scope) {
    $scope.save = function (user) {
        console.log(user.name);
    };

    $scope.user = {};

};

$(function () {
    $("button").button();
});

Upvotes: 4

Views: 2904

Answers (2)

Amani
Amani

Reputation: 525

This worked for me:

app.directive('jqButton', function() {
      return function(scope, element, attrs) {
          element.button();

          scope.$watch(attrs.jqButtonDisabled, function(value) {
              element.button("option", "disabled", value);
          });
      };
});

With this markup:

<input type="button" value="Button" jq-button jq-button-disabled="myForm.$invalid" />

Upvotes: 1

Ben Lesh
Ben Lesh

Reputation: 108471

Well the thing is with angular, you're supposed to be making directives to apply your JQuery plugins.

So here you could to this:

//NOTE: directives default to be attribute based.

app.directive('jqButton', {
   link: function(scope, elem, attr) {
      //set up your button.
      elem.button();

      //watch whatever is passed into the jq-button-disabled attribute
      // and use that value to toggle the disabled status.
      scope.$watch(attr.jqButtonDisabled, function(value) {
         $("button" ).button( "option", "disabled", value );
      });
   }
});

and then in markup

<button jq-button jq-button-disabled="myForm.$invalid" ng-click="doWhatever()">My Button</button>

Upvotes: 6

Related Questions