Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ng-click with multiple expressions? [duplicate]

I want to use ng-click to perform multiple expressions. I want to both set a value on a model, and call a method from the $scope, like this:

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

Where I have && separating the two different expressions I want to perform. I know I could just add a method that does both things in the controller. Should I just do that, or is there a way to perform two expressions directly from inside ng-click?

like image 987
CorayThan Avatar asked Nov 11 '13 19:11

CorayThan


2 Answers

Simply 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> 
like image 200
urish Avatar answered Sep 21 '22 04:09

urish


You can write only expression into ng-click.

The ngClick directive allows you to specify custom behavior when an element 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 book content.

Demo Fiddle

Reference

We have several options here to invoke navigation.book = book

What's happen if we will write:

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

In this case if (seems like bookSvc is a service) bookSvc.showBook(book) returns nothing or false, the navigation.book = book will never execute.

Demo 2 Fiddle

But if bookSvc.showBook(book) returns true the navigation.book = book will be invoked.

Demo 3 Fiddle

like image 29
Maxim Shoustin Avatar answered Sep 20 '22 04:09

Maxim Shoustin