简体   繁体   中英

How should you define regular functions in AngularJS

I have some experience in AngularJS, but the fact that I can't figure out how to handle a regular function inside a AngularJS controller keeps bothering me. For the record I am talking about a function that handles parts of small business logic inside the controller, that doesn't need to be shared across controllers. I have found two ways to handle such regular functions that don't need binding from the view.

The first way I have found is to just use: $scope.myFunction = function(){} but the fact that it can be used directly from the view doesn't seem correct.

The second way I have found is to just use a regular Javascript function: function myFunction(){} but I don't know how the visibility of such functions is in AngularJS.

Is there a "correct" way of ensuring a limited visibility inside a controller? Or should I keep using the regular Javascript function?

Just the same way as you would define a "local" function within a standard closure:

myApp.controller("MyCtrl", ["$scope", function($scope) {
    var localFunc = function() {
        // Internal function, only available to code executed after
        // localFunc is declared
    };
    function localFuncHoisted() {
        // Internal function, doesn't matter where it is declared
        // will be visible to all internal methods
    }
    $scope.globalFunc = function() {
        // Available from the controller
    }
}]);

localFunc and localFuncHoisted are identical in most cases, however each has its own benefits. The hosted function is visible to all code, before and after declaration. localFunc can be set only when needed and removed when not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM