Search code examples
angularjsfunctioncall

Can you put a function call in an AngularJS expression?


I am following W3School's Angular course and I am confused as to why I cannot put a function call in an Angular expression -just for fun even if may not be best practice if I find that out later:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
function add() { return 5+5 }
</script>
<body>

<div ng-app>
<p>My first expression: {{ add() }}</p>
</div>

</body>
</html>

Solution

  • You can, but the function needs to be defined in the controller since that is where the {{ }} notation directs Angular to look.

    angular.module('app', [])
      .controller('ctrl', function() {
        this.add = () => {
          return 5 + 5;
        }
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
    <div ng-app="app" ng-controller="ctrl as $ctrl">
      {{ $ctrl.add() }}
    </div>