代码之家  ›  专栏  ›  技术社区  ›  George Cimpoies

在angularjs中从一个控制器调用另一个控制器的函数

  •  0
  • George Cimpoies  · 技术社区  · 8 年前

    我目前有两个javascript控制器:selectAll和listAllDomains。 我试图在控制器selectAll中调用方法getBeanName(在listAllDomains中定义),该控制器位于:

    response = $http.post('/invoke/selectAll/', INSERT_CALL_HERE);
    

    注意,getBeanName方法返回的对象将作为参数传递给$http。post()方法并由Java控制器处理。

    app.controller('listAllDomains', ['$http', '$scope', '$rootScope', function ($http, $scope, $rootScope) {
        $scope.showSpinner = true;
        $scope.showBtn = false;
        let dataObj;
    
        $http.get('domains/').then(function (response) {
            $scope.showSpinner = false;
            $scope.domains = response.data;
        });
    
        $scope.showButton = function(eleStatus) {
            let eleSize = Object.keys(eleStatus).length;
            return !eleSize;
        };
        $scope.getBeanName = function (objectType, objectName) {
    
            dataObj = {
                type : objectType,
                name : objectName,
                methodName : "select",
                methodParameters : ["true"]
            };
    
            localStorage.setItem("dataObj", dataObj);
            console.log(dataObj);
            $rootScope.$emit("invokeSelectAll", dataObj);
    
            return dataObj;
        }
    }]);
    
    
    
    
    app.controller('selectAll', ['$http', '$scope' , '$rootScope',
        function ($http, $scope, $rootScope) {
    
        var response;
    
        $rootScope.$on("invokeSelectAll", function(){
            $scope.invokeSelectAll();
        });
    
        $scope.invokeSelectAll  = function(){
            console.log(localStorage.getItem("dataObj"));
            response = $http.post('/invoke/selectAll/', INSERT_CALL_HERE);
    
            response.success(function(data, status, headers, config) {
                $scope.responses = data ? data : "Select Operation not supported on this bean";
            });
        }
    
    
    }]);

    2 回复  |  直到 8 年前
        1
  •  0
  •   anteAdamovic    8 年前

    您可以创建一个服务并将其注入两个控制器,也可以只在$rootScope中定义您的函数,然后在任何控制器中使用它。

    检查此问题以供参考: How to use $rootScope in AngularJS

        2
  •  0
  •   Ramesh Lamba    8 年前

    首先创建具有所需功能的服务/工厂。然后注入控制器。