How to use ng-click with multiple expressions?

I want to use ng-click to execute multiple expressions. I want to both set the value on the model and call the method from $scope , for example:

 <a ng-click="navigation.book = book && bookSvc.showBook(book)" href="#{{book.id}}">{{book.title}}</a> 

Where I && share two different expressions that I want to execute. I know that I can simply add a method that performs both functions in the controller. Should I just do this or is there a way to execute two expressions directly from within ng-click ?

+53
javascript angularjs angularjs-ng-click
Nov 11 '13 at 19:32
source share
3 answers

Just using ';' instead of '& &' to separate the expression should work for you:

 <a ng-click="navigation.book = book; bookSvc.showBook(book)" href="#{{book.id}}">{{book.title}}</a> 
+123
Nov 11 '13 at 19:53
source share

You can only write an expression in ng-click .

The ngClick directive allows you to specify custom behavior when an item is clicked.

But you can write:

 <a ng-click="( (navigation.book = book) && bookSvc.showBook(book))" href="#{{book.id}}">{{book.title}}</a> 

In this case, navigation.book gets the contents of the book .

Fiddle Demo

Link

We have several options for calling navigation.book = book

What happens if we write:

 ng-click="( bookSvc.showBook(book) && (navigation.book = book))" 

In this case, if (it seems that bookSvc is a service) bookSvc.showBook(book) returns nothing or false , navigation.book = book will never be executed.

Demo 2 Fiddle

But if bookSvc.showBook(book) returns true , navigation.book = book called.

Demo 3 Fiddle

+9
Nov 11 '13 at 19:42
source share

I would recommend putting all the logic in a function and just assign it ng-click to make the code simpler and more elegant.

+4
Nov 11 '13 at 19:55
source share



All Articles