简体   繁体   中英

Call function from one controller in another in angularjs

I currently have 2 javascript controllers: selectAll and listAllDomains. I'm trying to call the method getBeanName (defined in listAllDomains) in the controller selectAll under:

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

As a note, the object returned by the method getBeanName will be passed as an argument to the $http.post() method and handled by a Java controller.

 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"; }); } }]); 

Any help would be much appreciated! Thank you!

first create a service/factory with required function. And inject into the controller.

You can either create a service and inject it in both controllers or just define your function in $rootScope and then use it in any controller.

Check this issue for reference: How to use $rootScope in AngularJS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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