Function inside the AngularJS Controller

前端 未结 3 1656
暗喜
暗喜 2021-01-30 20:46

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

相关标签:
3条回答
  • 2021-01-30 20:52

    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.

    0 讨论(0)
  • 2021-01-30 20:55

    The definition is allowed, it has the same affect as

    $scope.$watch($scope.totalCart, function(){..some logic...})
    
    0 讨论(0)
  • 2021-01-30 21:06
    $scope.launch = function (which) {
    
    };
    var _func = function () {...}
    
    0 讨论(0)
提交回复
热议问题