在angularjs中从另一个控制器调用另一个控制器的功能

时间:2017-08-29 10:02:28

标签: javascript angularjs post http-post

我目前有2个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 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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