Angular js' $isEmpty functionality in form input

My code looks something like this -

<form name="myForm" ng-submit="!myForm.phone.$isEmpty(this.$viewValue)" action="/my/url" method="get">
<input name="phone">
<button type="submit">submit</button>
</form>

Now I can't submit the form even if I fill the phone number field.

But if I code like this :

<form name="myForm" ng-submit="!myForm.phone.$isEmpty(myForm.phone.$viewValue)" action="/my/url" method="get">
<input name="phone">
<button type="submit">submit</button>
</form>

Its perfectly working now.

So the difficulty is with 'this'. I cant even check the context of this, it should be the the context of $scope.myForm.phone, but somehow it isn't. Can someone please explain.

Upvotes: 2

Views: 3176

Answers (2)

Matt Herbstritt
Matt Herbstritt

Reputation: 4862

That's not what ng-submit is for. ng-submit is a function or expression called when the form is submitted. It's nothing to do with validation. If you want to ensure the text field is not empty before it's submitted you just need to add required and then if it is empty myForm.$invalid will be true.

Is this what you are trying to do:

html

<form name="myForm" ng-submit="submit(phone)">
    <input name="phone" type="text" ng-model="phone.value" required>
    <button type="submit" ng-disabled="myForm.$invalid" >submit</button>
</form>

controller

$scope.submit = function(phone){
    console.log('phone', phone);
}

$scope.phone = {
    value: ''
};

update

The this that you passed into the ng-submit is a reference to your controller. Since you have the name attribute set to myForm you can access the form model via this.myForm and the phone model via this.myForm.phone. So if you wanted to use $isEmpty to verify if the field is empty you would have to use:

this.myForm.phone.$isEmpty(this.myForm.phone.$viewValue)

Upvotes: 3

Kirill Slatin
Kirill Slatin

Reputation: 6143

ng-submit is used to provide a handler for the moment when the form IS submitted. What you're looking for is disabling submit button with ng-disabled

<form name="myForm" ng-submit="functionInController()" action="/my/url" method="get">
<input name="phone" required>
<button type="submit" ng-disabled="myForm.$invalid">submit</button>
</form>

Pay attention to required directive added to the input. Which makes sure this field is not empty for submit

Upvotes: 2

Related Questions