AliOli
AliOli

Reputation: 571

Some assignment operators don't work in AngularJS expressions.. why not?

The AngularJS docs only list four differences between Angular expressions and JS expressions (docs):

  1. Attribute evaluation (against scope instead of global window);
  2. Forgiving (to undefined and null);
  3. No control flow statements allowed;
  4. Filters (results of expression evaluation can be passed through filter chain).

But arithmetic assignment operators also don't work inside an expression. For example, "plus-equals" += and "minus-equals" -= raise an error on the constant after the equals-sign.

Is there a particular reason why these assignment operators would be problematic to allow in expressions? Or would this simply be a matter of implementation priorities?

Is there perhaps an Angular-specific way of incrementing and decrementing? Currently, people seem to be left to typing the full somelongname = somelongname + x, or defining increment and decrement as functions in a controller. The same goes for other arithmetic assignment operators.

A short example of what I'm using to increment and decrement as workaround. It works, but is it elegant?

In controller:

$scope.incr = function(number, constant){
    $scope[number] += constant;
};
$scope.decr = function(number, constant){
    $scope[number] -= constant;
};

In HTML:

<button class="btn" ng-disabled="currentPage == 0" ng-click="decr('currentPage', 1)">

Upvotes: 2

Views: 3778

Answers (1)

Mark Rajcok
Mark Rajcok

Reputation: 364707

Is there a particular reason why these assignment operators would be problematic to allow in expressions? Or would this simply be a matter of implementation priorities?

I would say it is a combination of

  1. implementation priorities (see Brad and Igor video talking about expression support in v1.2) and
  2. what @Sharondio mentioned in the comment above: the view is normally not the place for expressions – the controller is.

Upvotes: 1

Related Questions