Skip to content Skip to sidebar Skip to footer

Using A Variable Within Angularjs Expression?

I'm new to Angular, but I was wondering am I able to use a JS variable within an AngularJS expression (not sure if it's called an expression). The simplest way I can demonstrate is

Solution 1:

No, you cannot use global variables (or functions) in Angular expressions. Angular expressions are just attributes, so are strings and not Javascript code. Angular parser ($parse service, sourse code) takes those attributes, parses them and evaluates against scope object of the Angular app. So in order to use anything in Angular expression it must be defined on the corresponding scope object.

Solution 2:

You are not supposed to. You are going to kill the whole purpose of Angular if you do so. And won't work how you put it. Still I made a Plunker for you here. After all a global JavaScript variable can be access from inside your controller if it was defined before your controller code.It is all JavaScript after all

http://plnkr.co/edit/LiwvNd4Nf5lW0HUsSyyq?p=preview

in HTML

<script>var x = 7;
</script>

and in controller

// in the controller$scope.Foo=function(){
      return$scope.Page + x;
    }

Post a Comment for "Using A Variable Within Angularjs Expression?"