首页 > 解决方案 > 如何从不同的控制器调用另一个控制器的功能

问题描述

我使用 angular js 作为我的客户端。我想调用另一个控制器中的一个函数。我怎样才能做到这一点?

标签: angularjsfunctioncontrollerinvoke

解决方案


var app = angular.module('MyApplication', []);
app.controller('Controller1', function($scope, $rootScope) {
  $scope.function1 = function() {
    console.log('Controller 1 clicked and Function 1 called');
  }
  //receive the fuction using $on MyFunction
  $rootScope.$on("CallController1", function() {
    console.log('Controller 2 clicked and Controller 1 called');
  });
});
app.controller('Controller2', function($scope) {
  $scope.function2 = function() {
    console.log('Controller 2 clicked and Function 2 called');
    $scope.$emit("CallController1"); //emit the fuction using MyFunction
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="MyApplication">
  <div ng-controller="Controller1">
    <button ng-click="function1()">function 1</button>
  </div>
  <br>
  <div ng-controller="Controller2">
    <button ng-click="function2()">function 2</button>
  </div>
</div>


推荐阅读