Anes El Gongi
Anes El Gongi

Reputation: 48

AngularJS - dynamic validation using $valid

I'm using AngularJS to validate a form, and I have this button to submit.

<button type="submit" ng-disabled="btn" ng-click="submit(settings.$valid)"
        class="btn btn-primary">
  Submit
</button>

This button is disabled whenever the form is invalid, but once it's valid, the button is enabled.

So this is my code

$http.get("http://localhost:5000/settings").then(function(response){
    $scope.numberOfRows = response.data.numberOfRows
    console.log($scope.numberOfRows)
    if($scope.numberOfRows==0 && $scope.settings.$valid == false ){
        $scope.btn=true
    }else if($scope.numberOfRows==0 && $scope.settings.$valid == true){
        $scope.btn=false
    }

    if($scope.numberOfRows==1){
        $scope.btn=true
    }

})

My problem is when the numberOfRows = 0 and the form is invalid, I can't submit the form which what I want.

BUT, when I fill my form and it became valid, nothings happend.

Can you help me ?

Upvotes: 0

Views: 72

Answers (1)

Ramin Farajpour
Ramin Farajpour

Reputation: 417

$http.get("http://localhost:5000/settings").then(function(response){
    $scope.hasRow= response.data.numberOfRows>0;
    $scope.settings.$valid=$scope.hasRow;
})

and add this code to your html

 <button type="submit" ng-disabled="!settings.$valid" ng-click="submit()"
        class="btn btn-primary">
  Submit
</button>

Upvotes: 1

Related Questions