使用 AngularJS 和表单验证禁用 jQuery 按钮 [英] Disable jQuery Button with AngularJS and Form Validation
问题描述
我想根据表单验证禁用我的 jQuery 按钮.根据文档,这对于使用以下语法的常规按钮相当容易:
<button ng-click="save(user)" ng-disabled="form.$invalid">保存</button>
但是,当更改为 jQuery UI 按钮时,这不再起作用.我假设 Angular 在 jQuery UI 和 AngularJS 之间没有真正的绑定,因此需要一个指令来执行以下操作:
$("button" ).button( "option", "disabled" );
是这种情况还是有其他选择?我正在尝试做的 jsFiddle 在这里:http://jsfiddle.net/blakewell/vbMnN/.
我的代码如下所示:
查看
<form name="form" novalidate class="my-form">名称:<input type="text" ng-model="user.name" required/><br/>电子邮件:<input type="text" ng-model="user.email" required/><br/><button ng-click="save(user)" ng-disabled="form.$invalid">保存</button></表单>
控制器
function MyCtrl($scope) {$scope.save = 函数(用户){控制台日志(用户名);};$scope.user = {};};$(函数(){$("按钮").button();});
问题在于 angular,你应该制定指令来应用你的 JQuery 插件.
所以你可以这样做:
//注意:指令默认是基于属性的.app.directive('jqButton', {链接:函数(范围,元素,属性){//设置你的按钮.elem.button();//观察传递到 jq-button-disabled 属性的任何内容//并使用该值切换禁用状态.scope.$watch(attr.jqButtonDisabled, function(value) {$("button" ).button( "option", "disabled", value );});}});
然后在标记中
<button jq-button jq-button-disabled="myForm.$invalid" ng-click="doWhatever()">我的按钮</button>
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();
});
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>
这篇关于使用 AngularJS 和表单验证禁用 jQuery 按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!