[英]$emit + $on / $broadcast + $on are not working in AngularJS
我需要在 angular js 中調用另一個控制器中的函數。請幫助我,我使用了下面的代碼,但它不起作用,請幫助我
routerApp.controller('EmployeeController', function ($scope, $rootScope) {
$rootScope.$on("CallSearchtMethod", function (searchName) {
$scope.parentmethod(searchName);
});
$scope.parentmethod = function (searchName) {
console.log("data is" + searchName);
}
}
})
routerApp.controller('navCtrl', function ($scope,$rootScope ) {
$scope.searchFun = function (searchName) {
$rootScope.$emit("CallSearchtMethod", searchName);
}
})
您應該使用Service 。 它的作用是允許您創建將在許多地方使用的通用功能,在這種情況下是控制器。
這是一個示例工作代碼片段,將指導您執行服務。
angular.module('starterByAR', ['starterByAR.controllers', 'starterByAR.services']); angular.module('starterByAR.controllers', []) .controller('mainOne', [ '$scope', 'myService', function($scope, myService) { $scope.text = myService.commonFunction(); } ]) .controller('mainTwo', [ '$scope', 'myService', function($scope, myService) { $scope.text = myService.commonFunction(); } ]); angular.module('starterByAR.services', []).service('myService', function() { return { commonFunction: function(){ return 'Some Text'; } }; });
<head> <title>Angular Starter</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <body ng-app="starterByAR"> <div ng-controller="mainOne"> Here is {{text}} from Controller 1 </div> <div ng-controller="mainTwo"> Here is {{text}} from Controller 2 </div> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.