Gilad Green Gilad Green - 1 month ago 18
AngularJS Question

ng-click only where paper-input form is valid

I'm new to web and can't figure this one out:

I have a form that I want the submit button to be disabled while the form is invalid.
I've tried using the X.$valid and the X.checkValidity() but with no help. I've also looked at the iron-form examples and documentation but I can't

I assume my trouble is the use of Angular + Polymer but I can't find a solution to how to get the behavior I want.

here is my code:



<form id="loginForm" novalidate>
<paper-input ng-model="username" label="{{::tr('Enter a username')}}" required auto-validate error-message="{{::tr('Please enter your username')}}" ng-keyup="keyPress($event.keyCode)" ng-change="password = ''"></paper-input>
<paper-input ng-model="password" label="{{::tr('Enter a password')}}" required auto-validate error-message="{{::tr('Please enter your password')}}" type="password" ng-keyup="keyPress($event.keyCode)"></paper-input>
<div id="loginFailureReason"></div>
<div class="pm4-form-footer">
<paper-button raised ng-click="forgotPassword();" ng-enable="!loading">{{::tr('Forgot your password') }}</paper-button>
<paper-button raised type="submit" ng-click="loginForm.$valid && login()" ng-enable="loginForm.$valid && !loading">{{::tr('Sign in')}}</paper-button>
</div>
</form>





Code of the controller:

loginApp.controller('LoginController', ["$scope", "$http", "$window","trFilter",
function ($scope, $http, $window, tr) {
//Used to determine if to present the reset password form or not
$scope.resettingPassword = false;
//Used to determine if to present the reset code form or not
$scope.submitResetCode = false;

//Model fields that will be sent to server
$scope.username = '';
$scope.password = '';

$scope.login = function () {
$scope.loading = true;
$('input[ng-model], select[ng-model]').each(function () {
angular.element(this).controller('ngModel').$setViewValue($(this).val());
});
$http.post('/Account/DoLogin', { username: $scope.username, password: $scope.password }).
success(function (data, status, headers) {
if (headers('AccountCtrResponse') !== null && headers('AccountCtrResponse') === "Done") {
$window.location.replace("/" + $window.location.hash);
} else {
$scope.logonFailureReason = tr("Login failed due to the following reason: " +headers('AccountCtrResponse'));
$scope.loading = false;
}
}).
error(function () {
$scope.logonFailureReason = "Failure in submitting the request. Try again later or report this if it persists.";
$scope.loading = false;
});
};

Answer

If I add the following code it works but I think it is incorrect to put that logic in the controller. In the html:

<paper-button id="submitionButton" raised type="submit" ng-disabled="!formValidity()">
    {{::tr('Sign in')}}
</paper-button>

In the controller:

$scope.formValidity = function () {
    return loginForm.checkValidity();
};
Comments