Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ES6 arrow functions in AngularJS html templates

is there a posibility to use ES6 arrow functions directly in AngularJS html tamplates like this ?

<div ng-if="results.filter(e => e.ext == 'xml').length > 0">Text</div>

'result' is a list of objects with 'ext' as property. Until now I've used lodash and it works perfectly:

<div ng-if="_.filter(results, { ext : 'xml' }).length > 0">Text</div>

but will change to ES6 if possible...

Has anybody experience with that or some hints or maybe better ideas ?

like image 331
walko1234 Avatar asked Oct 18 '22 05:10

walko1234


2 Answers

The ng-if directive evaluates an AngularJS Expression and function declarations are not allowed.

From the Docs:

AngularJS Expressions vs. JavaScript Expressions

AngularJS expressions are like JavaScript expressions with the following differences:

  • No Function Declarations: You cannot declare functions in an AngularJS expression, even inside ng-init directive.

If you want to run more complex JavaScript code, you should make it a controller method and call the method from your view. If you want to eval() an AngularJS expression yourself, use the $eval() method.

— AngularJS Developer Guide - Expressions

like image 177
georgeawg Avatar answered Oct 21 '22 03:10

georgeawg


No, as georgeawg has said, you can't declare functions at all inside an Expression (e.g inside an 'ng-if'). This is partly because Angular is designed to encourage any business logic to be placed in the controller, to encourage correct separation of concerns.

Angular Expressions are limited to fairly basic things like accessing properties of objects or values on the scope, and basic formatting, sorting and filtering. Any business logic definitions belong in the controller.

like image 22
Chris Halcrow Avatar answered Oct 21 '22 03:10

Chris Halcrow