r/angularjs • • Sep 07 '16

Dissecting a favorite interview question: How would you implement ng-click

http://www.codelord.net/2016/09/06/angular-interview-question-deep-dive-implement-ng-click/
53 Upvotes

9 comments sorted by

1

u/10gistic Sep 08 '16

Depending on your use case, $eval is probably better yet. You don't know when the expression might change (say, swapping out functions of the same name on the $scope), and $parse is only going to evaluate once, rather than every click event.

Some efficiency trade-off obviously applies here, but it's probably the least likely to surprise your users (or yourself) with its behavior.

3

u/abyx Sep 08 '16

FWIW, here's the ng-click code showing Angular itself uses $parse.

1

u/10gistic Sep 08 '16

Ah, good call. I'd forgotten that $parse simply compiles the expression and it's still evaluated every time the function is called. That is indeed the best way to go. (Gonna have to do some minor refractors tomorrow)

If anybody's interested in a good coffee shop read, I definitely recommend giving the $parse code a once over. Or maybe twice over.

Funny thing is, once you read that code, it's completely unsurprising that the Angular team started thinking about writing a new language (atscript for the unfamiliar) for Angular 2.

1

u/[deleted] Sep 08 '16

Atscript was not a new language by any means, it was simply a superset of javascript...just like typescript.

1

u/10gistic Sep 08 '16 edited Sep 08 '16

Well as supersets of the language they are clearly not equivalent languages. And atscript was not an existing variant; thus my use of the word "new."

1

u/_Aardvark Sep 08 '16

On an somewhat related note, anyone ever look at the angular code where they define all the ng-eventhandler directives. Where they iterate over an array of event names to define each directive with the same code.

Not groundbreaking, I just thought it was clever.

1

u/abyx Sep 08 '16

Yeah I agree. I linked to it in a comment above

2

u/benny-powers Sep 07 '16

Cool example thanks

1

u/[deleted] Sep 08 '16

great example. thanks

and I think ng-click somehow commonly used when it comes to submit/triggering something thinggie