Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement in ng-click

Is there a way to put a condition inside an ng-click? Here, I want that the form is not submitted if there are any form errors, but then I got a parse exception.

 <input  ng-click="{{if(profileForm.$valid) updateMyProfile()}}" name="submit" id="submit" value="Save" class="submit" type="submit"> 

I tried to use ng-disabled but then my validation plugin does not work cause form is never submitted at all, so it is not triggered.

like image 461
Spring Avatar asked Feb 14 '14 18:02

Spring


People also ask

Can we put condition in NG-click?

We can add ng-click event conditionally without using disabled class.

What does ng-click do?

ng-click is an attribute of an HTML element that can be used for the customized components in Angular. We use this attribute to detect if an element is clicked and tracks the mouse's cursor. ng-click takes a function as an attribute and calls it whenever an element is clicked.

What is data ng-click?

The ng-click directive tells AngularJS what to do when an HTML element is clicked.

Can we use NG-click and Onclick together?

For a single btn, it's ok to use ng-click or onclick in the ng-app . There is no difference between the two functions. For effective team work, you,d better to have an account with each other. In Angular apps, ng-click is recommended.


2 Answers

Don't put any Condition Expression in Template.

Do it at the Controller.

Template:

<input ng-click="check(profileForm.$valid)" name="submit"         id="submit" value="Save" class="submit" type="submit"> 

Controller:

$scope.check = function(value) {     if (value) {        updateMyProfile();     } } 
like image 109
Chen-Tsu Lin Avatar answered Sep 20 '22 12:09

Chen-Tsu Lin


This maybe irrelevant and of no use, but as it's javascript, you don't have to use the ternary as suggested above in the ng-click statement. You should also be able to use the lazy evaluation ("or die") syntax as well. So for your example above:

<input  ng-click="{{if(profileForm.$valid) updateMyProfile()}}" name="submit" id="submit" value="Save" class="submit" type="submit"> 

would become:

<input  ng-click="profileForm.$valid && updateMyProfile()" name="submit" id="submit" value="Save" class="submit" type="submit"> 

In this case, if the profile is not valid then nothing happens, otherwise, updateMyProfile() is called. Like in the link @falinsky provides above.

like image 41
Rob Wilson Avatar answered Sep 20 '22 12:09

Rob Wilson