5

If I want to refer to my angular controller function from a template, I should put the function in $scope, like this:

[template]
<button ng-click="doSomething()"></button>

[controller]
$scope.doSomething = function(){};

But what about other functions (and controller variables that I don't need to be watched), the ones that I will not reference in templates.

Should I put them all in '$scope' too? Isn't it bad for performance? Is there any gotchas in declaring such functions outside of $scope?

7
  • 1
    You should not put them in scope. Just define them inside controller like regular functions and variables. Commented Nov 16, 2014 at 13:54
  • @MadhurAhuja like this.myFunction=.. or var myFunction=...? Commented Nov 16, 2014 at 13:55
  • I prefer function myFunction() {... }. The problem with var myFunction=... is that it can be called only after where it is declared. Commented Nov 16, 2014 at 14:01
  • this.myFunction will be part of scope. Commented Nov 16, 2014 at 14:01
  • 1
    What @charlietfl means is this: codetunnel.io/angularjs-controller-as-or-scope - check it out ;) Commented Nov 16, 2014 at 14:05

1 Answer 1

5

You can simply define those as private functions within the controller's function.

Note that I also favor the function declaration syntax rather than assigning a function expression to a variable because it allows you to have all your functions declared at the bottom which reduces cognitive load when trying to see what's going on.

app.controller('MainCtrl', function ($scope) {
  $scope.exposedFn = exposedFn;

  function exposedFn() {
      fnNotExposed();
  }

  function fnNotExposed() {}

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

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.