Function inside the AngularJS Controller
Solution 1:
The calculate()
is a private function -- it is only accessible in the scope of CartController
. If you do not need to make use of your function in the view it is good idea to make it private. It says that it is not intended to be used in the view, so if someone else will be working with this code should think twice before use it in the view. Moreover: from within calculate
you have access to all objects that are accessible in the scope of the CartController
(including objects passed to CartController
as parameters).
Function declared in this way is a proper JS function
, which means you can get reference to it by its name. Sometimes it is thought to be more readable if you declare / create your function in advance and only then assign them to properties of some other object (in this case $scope
):
function someFn (...) { ... }
function someOtherFn (...) { ... }
...
$scope.someFn = someFn
In the above snippet the intentions are very clear: make someFn
accessible, while keep someOtherFn
private.
Btw. declaring functions like: function nameFn(...){...}
is called function statement; you can very similarly do it like: var nameFn = function(...) {...}
(so called function expression). There is a slight difference between those -- basically it is illegal:
someFn();
var someFn = function(...) {...}
whereas, this works:
someFn();
function someFn(...) {...}
Sometimes you are forced to use this pattern, look e.g. at my answer to this question.
Solution 2:
$scope.launch = function (which) {
};
var _func = function () {...}
Solution 3:
The definition is allowed, it has the same affect as
$scope.$watch($scope.totalCart, function(){..some logic...})