简体   繁体   English

你应该如何在AngularJS中定义常规函数

[英]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. 我在AngularJS方面有一些经验,但事实上我无法弄清楚如何在AngularJS控制器中处理常规函数一直困扰着我。 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. 我找到的第一种方法是使用: $scope.myFunction = function(){}但是它可以直接从视图中使用的事实似乎不正确。

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. 我找到的第二种方法是使用常规的Javascript函数: function myFunction(){}但我不知道这些函数在AngularJS中的可见性。

Is there a "correct" way of ensuring a limited visibility inside a controller? 是否有“正确”的方法来确保控制器内部的可见性有限? Or should I keep using the regular Javascript function? 或者我应该继续使用常规Javascript函数?

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. 在大多数情况下, localFunclocalFuncHoisted是相同的,但每个都有自己的好处。 The hosted function is visible to all code, before and after declaration. 在声明之前和之后,托管函数对所有代码都可见。 localFunc can be set only when needed and removed when not. localFunc只能在需要时设置, localFunc可以删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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