Disable jQuery Button with AngularJS and Form Validation

空扰寡人 提交于 2019-12-12 09:41:09

问题


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

回答1:


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>



回答2:


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" />


来源:https://stackoverflow.com/questions/14607912/disable-jquery-button-with-angularjs-and-form-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!