Ng-disabled with a function that fires on change

I have a submit confirmation button that should be enabled when all fields are entered correctly. Since validation is too complex and cannot be resolved with formName. $ Invalid alone, I need to write a function for validation. I expect the shouldEnable function to become a trigger for each of the model changes inside. But this is not so. Is there an alternative for this?

Initial

<button ng-disabled="formName.$invalid">Submit</button>

Expected

<button ng-disabled="shouldEnable()">Submit</button>

$scope.shouldEnable = function() {
    $scope.isEnable = true;
    angular.forEach($scope.form.input2, function(val) {
        if($scope.form.input2.inputA && $scope.form.input2.inputB) {
            isEnable = false;
        }
    })
}
+4
source share
2 answers

Your function should return a boolean:

$scope.shouldEnable = function() {
    var isEnable = true;
    // make necessary checks
    return isEnable;
}
+4
source

If you are using Angular data binding, you should use something like this:

<button ng-disabled="shouldEnable">Submit</button>

// yourObject is the object you've map in the form
$scope.$watch('yourObject', function(newObject) {
   $scope.shouldEnable = isValid(newObject);
});
0

All Articles