0

Simple question about syntax. In Angular, I've seen functions inside a controller created like this:

this.multiply = function multiply(a, b) {
    return a * b; 
}

I'm a bit thrown of since the function is given a name and also assigned to a variable with. So my question is why are functions assigned to variables in Angular? Does this affect scope?

5
  • 2
    it just makes them publicly accessible to whoever has an instance to the controller. Commented Jun 7, 2015 at 23:17
  • Why the down votes ? It's a valid question. Commented Jun 7, 2015 at 23:18
  • More commonly you'll create something on scope in the viewmodel (controller) so your view has access to it (e.g. a click handler). Commented Jun 7, 2015 at 23:18
  • @DanielA.White, if you post your comment as an answer, I can accept it. Thanks. Commented Jun 7, 2015 at 23:19
  • To the people that keep down-voting, it would be helpful if you could illuminate what your problem with the question is. Commented Jun 8, 2015 at 15:18

2 Answers 2

3

This is standard JavaScript and this is called Named function Expression.

By using this you are defining it on controller. If you use controlleras syntax in views or while defining routes you can use such functions as well as any properties defined on this.

Earlier versions of Angular only employed $scope and everything had to be defined on $scope.

Now the controller itself is instantiated on scope depending upon controller name alias in controlleras

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

Comments

1

It isn't assigning it to a variable. It is assigning it to the instance of the controller, with this; so whoever has an instance of the controller can call it.

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.