ImpostorIsAsking
ImpostorIsAsking

Reputation: 73

AngularJS: Using function in ng-disabled

I'm using ng-disabled in my view like this I have truthy conditions

 md-button.md-primary.md-raised flex="20" ng-disabled="form.$invalid || form.$pristine || day == 0 || leaveapplication.reason == null" ng-click="save(starts_on, ends_on, leave_type_id, period1, period2)" Apply

So I'm gonna use function in my ng-disabled this time:

 md-button.md-primary.md-raised ng-disabled="buttonChecker()" ng-click="save(starts_on, ends_on, leave_type_id)" Apply

Now how can I put my condition in my function like form.$valid and form.$pristine the other condition is easy like day == 0, but the other conditions are hard for me.

Upvotes: 3

Views: 3080

Answers (2)

Jhim
Jhim

Reputation: 44

Try passing the form on your function.

 md-button.md-primary.md-raised ng-disabled="buttonChecker(formName)" ng-click="save(starts_on, ends_on, leave_type_id)" Apply

and have the buttonChecker check the form using

$scope.buttonChecker = function (formName) {
  return formName.$invalid || formName.$pristine;      
};

Upvotes: 0

lin
lin

Reputation: 18392

Just access it with $scope where the name of the form is binded to $scope.nameOfForm. I don't know where your other variables like day or leaveapplication.reason are defined so I just inserted them blankly. You have to edit this part to make it work but I think this will show you how to achieve what you trying to.

View

<div ng-controller="MyCtrl">
  <form name="myForm">
      <input type="text" name="test" ng-model="test">
      <button ng-disabled="buttonChecker();">
        Some Button
      </button>
  </form>
</div>

AngularJS Application

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.buttonChecker = function () {
      return $scope.myForm.$invalid 
                || $scope.myForm.$pristine 
                || $scope.day === 0 
                || $scope.leaveapplication.reason === null;
    };
});

> Demo fiddle

Upvotes: 2

Related Questions