2

Is there some way to evaluate AngularJS expressions in the context of a controller, service, or directive, like a filter?

I rather like the fact that expressions are very elegant when mashing data, especially deeply nested objects with optional keys.

Something like:

$expression("[foo.bar.bar, foo.bar.baz, foo.bar] | lowercase", object);

2
  • AngularJS expression is functional code, it is not a statement. Commented May 23, 2014 at 17:11
  • @Husky: Did you take a look at my answer ? Did it solve the problem ? Commented May 31, 2014 at 8:01

1 Answer 1

2

You can use a filter in JS with the $filter service:

.controller('someCtrl', function ($filter, $scope) {
    $scope.lower = $filter('lowercase')('HELLO, WORLD !');
    // -> $scope.lower will be 'hello, world !'
});

If you don't want to use a filter, but evaluate an expression (although I can't think of any good reason), you can use $scope.$eval():

.controller('someCtrl', function ($scope) {
    $scope.someProp = 'HELLO, WORLD !';
    $scope.lower = $scope.$eval('someProp | lowercase');
    // -> $scope.lower will be 'hello, world !'
});    
Sign up to request clarification or add additional context in comments.

8 Comments

Yes, i know that. But how do i use an expression?
I am not sure I understand. See my updated answer. Is that what you mean ? Basically, anything that could appear inside {{ }} in the view, can be passed to $eval() (omitting the {{ }}).
Maybe he means something like this: plnkr.co/edit/pJlFz4973sDUmhuF7WtY?p=preview
I use $scope.$eval to get values using the expression syntax because it avoids lots of isDefined/!= null testing..
Thanks! $scope.$eval was indeed exactly what i was looking for. Like @ScottWarren said, it's a more elegant and easier syntax than just using raw JS.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.