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
?
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() {}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With