0

我最近了解了 Angular.js。这里我将 Angular.js 与 Beego(Go 框架)集成来开发单页应用程序。我对如何在 Angular 控制器中自动调用方法感到困惑?

这是我的角度控制器:

angular.module('myApp')
    .controller('BarangMasukController', ['$scope', '$http', 'myServices', function ($scope, $http, myServices) {
        var initializeTask = function () {
            myServices.testAPI()
                .then(function (response) {
                    $scope.Sa = response.data.S;
                    $scope.Da = response.data.D;
                    console.log("Sa"+$scope.Sa);
                    console.log("Da"+$scope.Da);
                });
        }
        initializeTask();         
}]);

我的角度服务:

angular.module('myApp')
.factory('myServices', ['$http', function ($http) {
    return {
        //testapi
        testAPI: function () {
            return $http.get('/myapi');
        },
    };
}]);

我的角度路线:

angular.module('myApp').config(function($routeProvider, $locationProvider) {
    $routeProvider
    .when("/testAPI", {
      templateUrl: "static/views/penjualan/manage_penjualan.tpl",
      controller: 'BarangMasukController' 
    })
      .otherwise({
        redirectTo: '/'
      });

      $locationProvider.html5Mode(true);

  });

如您所见,我需要在控制器中手动调用方法 initializeTask()。当我的控制器中有多种方法时,就会出现问题。请帮忙。

4

1 回答 1

0

如果您希望自动调用您的方法,您可以使用 JavaScript 中的立即调用函数表达式 (IIFE),这是一个在定义后立即运行的函数。

(function () {
    // logic here
})();

有关详细信息,请参阅 Mozilla 开发人员指南。

如果您想将所有初始化逻辑放在一个方法中,并且如果您正在使用,components那么您可以使用 angularjs$onInit()生命周期钩子,该钩子将在元素上的所有控制器都已构建并初始化其绑定后自动被调用。更多信息可以在这里找到。

于 2018-10-04T06:57:05.133 回答