$ emit + $ on / $ broadcast + $ on在AngularJS中不起作用

时间:2018-12-25 03:46:06

标签: angularjs

我需要在angular js的另一个控制器中调用函数。如何可能的方法请帮助我,我使用了下面的代码,但它不起作用请帮助我某人

EmployeeCtrl

routerApp.controller('EmployeeController', function ($scope, $rootScope) {
        $rootScope.$on("CallSearchtMethod", function (searchName) {
            $scope.parentmethod(searchName);
        });
        $scope.parentmethod = function (searchName) {
            console.log("data is" + searchName);
        }
    }
})

NavCtrl

routerApp.controller('navCtrl', function ($scope,$rootScope ) {    
   $scope.searchFun = function (searchName) {
      $rootScope.$emit("CallSearchtMethod", searchName);
    }
})

1 个答案:

答案 0 :(得分:0)

您应该使用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>