Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS controller functions best practices

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?

like image 272
Anri Avatar asked Nov 16 '14 13:11

Anri


1 Answers

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() {}

});
like image 177
plalx Avatar answered Sep 27 '22 20:09

plalx