AngularJS controller uses best practices

If I want to access my angular control function from a template, I have to put the function in $scope , for example:

 [template] <button ng-click="doSomething()"></button> [controller] $scope.doSomething = function(){}; 

But what about other functions (and controller variables that I don’t need to look at), those that I will not reference in the templates.

Should I put them all in '$ scope' too? Isn't that bad for performance? Are there any errors when declaring such functions outside of $scope ?

+5
source share
1 answer

You can simply define them as private functions in a controller function.

Note that I also approve the syntax for declaring a function, rather than assigning a function expression to a variable, because it allows you to declare all your functions at the bottom, which reduces the cognitive load when trying to see what happens.

 app.controller('MainCtrl', function ($scope) { $scope.exposedFn = exposedFn; function exposedFn() { fnNotExposed(); } function fnNotExposed() {} }); 
+5
source

Source: https://habr.com/ru/post/1206978/


All Articles