7

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 ?

3
  • 2
    You can do that, angular evaluates any js expression in ng-if directive, but you shouldn't do that. Because there are many versions of browsers that do not support ES6. Commented Sep 17, 2017 at 19:54
  • 1
    @alexmac This is AngularJS and Expressions in AngularJS have limitations. See AngularJS Developer Guide - AngularJS Expressions vs. JavaScript Expressions. Commented Sep 17, 2017 at 22:44
  • Plenty of browsers support native ES6 now, go crazy with it. caniuse.com/#search=es6 Commented Aug 23, 2018 at 17:14

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

To clarify on calling eval() in an AngularJS expression, you can only call eval() from within an Expression, to evaluate something that itself is a valid expression. E.g. you can call $eval(expr) from the ng-if, but expr can only be a valid Angular expression defined in the controller e.g. '3*10|currency'
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.