I have code snippet in which there is a Angular Modular Controller, but there is a function inside the same controller and with a call, which is raising doubt in my mind that is this way of coding allowed in Javascript or Angular? If Yes then how does it read it? See the below code format I have:
obj.controller('CartController',function($scope){
$scope.totalCart = function(){
var total = 10;
return total;
}
function calculate(){
...Some Logic..
}
$scope.$watch($scope.totalCart, calculate);
)};
Please help me to understand that is this type of function definition and call within a controller allowed in Angular/Javascript?
AngularJS Controllers AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.
The primary responsibility of the controller is to create a scope object and thereby pass it to the view. With this, we come to an end of this AngularJS Controllers article.
If the two controller is nested in One controller. Then you can simply call: $scope. parentmethod();
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.
$scope.launch = function (which) {
};
var _func = function () {...}
The definition is allowed, it has the same affect as
$scope.$watch($scope.totalCart, function(){..some logic...})
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