AngularJS网页上的自调用JavaScript函数

4

我有一个用于AngularJS网页的自调用函数。如您所见,我有一个名为getData()的函数,其工作是在页面加载时以及随后根据用户与页面的交互进行ajax调用以获取一些数据。

<script type="text/javascript">
    // Should I defne it here like this completely outside the self invoking
    // function with or without var keyword
    getData = function (reqData) {
        alert(reqData); // Ajax call here...
    };

    (function () {

        // Should I defne it here like this? 
        getData = function (reqData) {
            alert(reqData); // Ajax call here...
        };

        //Should I have to use the var key word like so 
        var getData = function (reqData) {
            alert(reqData);// Ajax call here...
        };

        PatientCategoryController = function ($http, $scope, uiGridConstants) {

            // Should I defne it here like this inside the controller? 
            getData = function (reqData) {
                alert(reqData);// Ajax call here...
            };

            //Should I have to use the var key word inside the controller?
            var getData = function (reqData) {
                alert(reqData);// Ajax call here...
            };

            // Or should I define the function on the $scope object like so?
            $scope.getData = function (reqData) {
                alert(reqData);// Ajax call here...
            };

            angular.element(document).ready(getData('someDataToPass'));
        }
        PatientCategoryController.$inject = ['$http', '$scope', 'uiGridConstants'];
        angular.module('demoApp', ['ui.grid', 'ui.grid.autoResize', 'ui.grid.pagination']);
        angular.module('demoApp').controller('PatientCategoryController', PatientCategoryController);
    }());
</script>

我的问题是应该如何定义这个函数? 应该在$scope对象上定义吗? 还是应该与控制器并列定义? 或者应该将其完全定义在自调用函数之外?
还有类似的情况, 我应该在哪里定义javascript对象,以保存可能需要进行ajax调用的数据.
我开始构建这个页面,但某个时刻,javascript开始表现异常,所以我不得不从头开始。这就是我问这个问题的原因.
过去我阅读并尝试了解javascript,但除了浏览器端以外,我从未进行过任何严肃的javascript编程。这个应用程序本身是在Asp.Net mvc中的。所以我对javascript永远不感到自信,并且经常陷入这种麻烦中。请指导我。

1
这似乎是一个提出了许多可能性并询问哪一个是最好的问题。因此,这是一个带有个人观点的问题,因为其中多个选项可能都是正确的。 - Claies
2个回答

5

如果您希望这段代码是为控制器编写的,则可以按照我通常使用的模式进行操作。

(function () {
    'use strict';
    angular
        .module('moduleName')
        .controller('controllerName', controllerName);

    controllerName.$inject = ['$rootScope', '$scope'];

    function controllerName($rootScope, $scope) {
        var vm = this;
        //define your variables here

        activate();//self invoking method

        function activate(){
            //do whatever you want to do here
        }
    }
})();

希望这能帮上忙。

3

谢谢Mike的指导。正如我所说,我是一个新手,需要一些时间来尝试和实现。然后我会做必要的事情。 - VivekDev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接