frsv
frsv

Reputation: 65

Angularjs form in controller always undefined

In my project I use ui-view and with following structure (deleted unnecessary code):

<main class="content">
    <div class="inner" ng-controller="OrderPageController">
        <div ui-view="main-info"></div>
        <div ui-view="comments"></div>
        <div ui-view="bids-list"></div>
        <div ui-view="add-bid"></div>
    </div>
</main>

And in add-bid view:

<form name="newbidform" novalidate ng-submit="postNewBid(newbidform);">
   <input type="text" ng-model="newbid.bid" required>
   <input type="submit">
</form>

So, then I submit form I try to check if all of required inputs are valid:

$scope.postNewBid = function(form) {

console.log(form) // $valid and $invalid always undefined
console.log($scope.newbidform) // always undefined

        // check validity before send
        if (!form.$valid) {
            angular.forEach(form.$error, function (field) {
                angular.forEach(field, function(errorField){
                    errorField.$setTouched();
                })
            });
            $scope.failedSubmit = true;
            return false;
        } else {
            $scope.failedSubmit = false;
        } 
// other things if form is valid

So, the problem the form is always undefined (at all or $valid/$invalid attr). I tried to use formName as parameter in function, as $scope.formName variable (always undefined), and define controller twice, in second time on form:

<form name="newbidform" novalidate ng-submit="postNewBid();" ng-controller="OrderPageController">

Actually, it works, but when I'm trying to access other variables in controller - I can't. So, is there a way to get a form state in controller in AngularJs? Thanks

Upvotes: 1

Views: 1230

Answers (2)

charlietfl
charlietfl

Reputation: 171669

It sounds like your form is nested in child scope such as inside an ng-include or ng-if in which case since the form object doesn't exist in the parent scope the parent won't see it when angular creates it in the child.

You can fix it by simply creating an empty object in the parent controller and that object will be inherited by child scopes. Since the object exists now, a new object won;t need to be created and all the properties will get added to the reference in child scope.

$scope.newbidform ={};
$scope.postNewBid = function(form) {...

Upvotes: 1

Nicolas2bert
Nicolas2bert

Reputation: 1152

newbid is the variable you want to get, right ?

Try :

<form name="newbidform" novalidate ng-submit="postNewBid(newbid);">

Upvotes: 1

Related Questions