591

是否可以让一个控制器使用另一个控制器?

例如:

MessageCtrl此 HTML 文档仅打印文件中控制器传递的消息messageCtrl.js

<html xmlns:ng="http://angularjs.org/">
<head>
    <meta charset="utf-8" />
    <title>Inter Controller Communication</title>
</head>
<body>
    <div ng:controller="MessageCtrl">
        <p>{{message}}</p>
    </div>

    <!-- Angular Scripts -->
    <script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
    <script src="js/messageCtrl.js" type="text/javascript"></script>
</body>
</html>

控制器文件包含以下代码:

function MessageCtrl()
{
    this.message = function() { 
        return "The current date is: " + new Date().toString(); 
    };
}

它只是打印当前日期;

如果我要添加另一个控制器,DateCtrl它将特定格式的日期返回给MessageCtrl,那么将如何执行此操作?DI 框架似乎关注XmlHttpRequests和访问服务。

4

14 回答 14

710

控制器之间有多种通信方式。

最好的可能是共享服务:

function FirstController(someDataService) 
{
  // use the data service, bind to template...
  // or call methods on someDataService to send a request to server
}

function SecondController(someDataService) 
{
  // has a reference to the same instance of the service
  // so if the service updates state for example, this controller knows about it
}

另一种方法是在范围内发出事件:

function FirstController($scope) 
{
  $scope.$on('someEvent', function(event, args) {});
  // another controller or even directive
}

function SecondController($scope) 
{
  $scope.$emit('someEvent', args);
}

在这两种情况下,您也可以与任何指令进行通信。

于 2012-02-23T05:59:47.110 回答
123

看到这个小提琴:http: //jsfiddle.net/simpulton/XqDxG/

另请观看以下视频:控制器之间的通信

html:

<div ng-controller="ControllerZero">
  <input ng-model="message" >
  <button ng-click="handleClick(message);">LOG</button>
</div>

<div ng-controller="ControllerOne">
  <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
  <input ng-model="message" >
</div>

javascript:

var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
  var sharedService = {};

  sharedService.message = '';

  sharedService.prepForBroadcast = function(msg) {
    this.message = msg;
    this.broadcastItem();
  };

  sharedService.broadcastItem = function() {
    $rootScope.$broadcast('handleBroadcast');
  };

  return sharedService;
});

function ControllerZero($scope, sharedService) {
  $scope.handleClick = function(msg) {
    sharedService.prepForBroadcast(msg);
  };

  $scope.$on('handleBroadcast', function() {
    $scope.message = sharedService.message;
  });        
}

function ControllerOne($scope, sharedService) {
  $scope.$on('handleBroadcast', function() {
    $scope.message = 'ONE: ' + sharedService.message;
  });        
}

function ControllerTwo($scope, sharedService) {
  $scope.$on('handleBroadcast', function() {
    $scope.message = 'TWO: ' + sharedService.message;
  });
}

ControllerZero.$inject = ['$scope', 'mySharedService'];        

ControllerOne.$inject = ['$scope', 'mySharedService'];

ControllerTwo.$inject = ['$scope', 'mySharedService'];
于 2012-08-07T13:40:05.850 回答
56

如果您想将一个控制器调用到另一个控制器中,有四种方法可用

  1. $rootScope.$emit() 和 $rootScope.$broadcast()
  2. 如果 Second controller 是 child,则可以使用 Parent child 通信。
  3. 使用服务
  4. 一种 hack - 在 angular.element() 的帮助下

1. $rootScope.$emit() 和 $rootScope.$broadcast()

控制器及其作用域可能会被破坏,但 $rootScope 仍然存在于整个应用程序中,这就是我们采用 $rootScope 的原因,因为 $rootScope 是所有作用域的父级。

如果您正在执行从父母到孩子的沟通,甚至孩子想要与它的兄弟姐妹沟通,您可以使用 $broadcast

如果您正在执行从孩子到父母的通信,没有涉及兄弟姐妹,那么您可以使用 $rootScope.$emit

HTML

<body ng-app="myApp">
    <div ng-controller="ParentCtrl" class="ng-scope">
      // ParentCtrl
      <div ng-controller="Sibling1" class="ng-scope">
        // Sibling first controller
      </div>
      <div ng-controller="Sibling2" class="ng-scope">
        // Sibling Second controller
        <div ng-controller="Child" class="ng-scope">
          // Child controller
        </div>
      </div>
    </div>
</body>

Angularjs 代码

 var app =  angular.module('myApp',[]);//We will use it throughout the example 
    app.controller('Child', function($rootScope) {
      $rootScope.$emit('childEmit', 'Child calling parent');
      $rootScope.$broadcast('siblingAndParent');
    });

app.controller('Sibling1', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling one');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('Sibling2', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling two');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('ParentCtrl', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside parent controller');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

在上面的代码控制台中 $emit 'childEmit' 不会在子兄弟内部调用,它只会在父内部调用,其中 $broadcast 在兄弟和父内部也被调用。这是性能发挥作用的地方。$emit 是更可取的是,如果您使用子与父通信,因为它会跳过一些脏检查。

2.如果Second controller是child,可以使用Child Parent通信

它是最好的方法之一,如果您想在孩子想要与直系父母进行沟通的情况下进行孩子父母沟通,那么它不需要任何类型的 $broadcast 或 $emit 但如果您想进行父母与孩子之间的沟通,那么您必须使用 service 或 $broadcast

例如 HTML:-

<div ng-controller="ParentCtrl">
 <div ng-controller="ChildCtrl">
 </div>
</div>

Angularjs

 app.controller('ParentCtrl', function($scope) {
   $scope.value='Its parent';
      });
  app.controller('ChildCtrl', function($scope) {
   console.log($scope.value);
  });

每当您使用子与父通信时,Angularjs 将在子内部搜索一个变量,如果它不存在于内部,那么它将选择查看父控制器内部的值。

3.使用服务

AngularJS使用服务架构支持“关注点分离”的概念。服务是 javascript 函数,只负责执行特定任务。这使它们成为可维护和可测试的单个实体。用于使用 Angularjs 的依赖注入机制注入的服务。

Angularjs 代码:

app.service('communicate',function(){
  this.communicateValue='Hello';
});

app.controller('ParentCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Parent World");
});

app.controller('ChildCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Child World");
});

它将给出输出 Hello Child World 和 Hello Parent World 。根据服务单例的 Angular 文档 – 依赖于服务的每个组件都获得对服务工厂生成的单个实例的引用

4. 一种 hack - 在 angular.element() 的帮助下

此方法通过其 Id / 唯一 class.angular.element() 方法从元素获取 scope() 返回元素,并且 scope() 使用另一个控制器中的一个控制器的 $scope 变量给出另一个变量的 $scope 变量不是一个好习惯。

HTML:-

<div id='parent' ng-controller='ParentCtrl'>{{varParent}}
 <span ng-click='getValueFromChild()'>Click to get ValueFormChild</span>
 <div id='child' ng-controller='childCtrl'>{{varChild}}
   <span ng-click='getValueFromParent()'>Click to get ValueFormParent </span>
 </div>
</div>

Angularjs: -

app.controller('ParentCtrl',function($scope){
 $scope.varParent="Hello Parent";
  $scope.getValueFromChild=function(){
  var childScope=angular.element('#child').scope();
  console.log(childScope.varChild);
  }
});

app.controller('ChildCtrl',function($scope){
 $scope.varChild="Hello Child";
  $scope.getValueFromParent=function(){
  var parentScope=angular.element('#parent').scope();
  console.log(parentScope.varParent);
  }
}); 

在上面的代码中,控制器在 Html 上显示了它们自己的值,当您单击文本时,您将相应地在控制台中获取值。如果单击父控制器跨度,浏览器将控制子控制器的值,反之亦然。

于 2015-07-17T06:17:12.260 回答
52

这是两个控制器共享服务数据的单页示例:

<!doctype html>
<html ng-app="project">
<head>
    <title>Angular: Service example</title>
    <script src="http://code.angularjs.org/angular-1.0.1.js"></script>
    <script>
var projectModule = angular.module('project',[]);

projectModule.factory('theService', function() {  
    return {
        thing : {
            x : 100
        }
    };
});

function FirstCtrl($scope, theService) {
    $scope.thing = theService.thing;
    $scope.name = "First Controller";
}

function SecondCtrl($scope, theService) {   
    $scope.someThing = theService.thing; 
    $scope.name = "Second Controller!";
}
    </script>
</head>
<body>  
    <div ng-controller="FirstCtrl">
        <h2>{{name}}</h2>
        <input ng-model="thing.x"/>         
    </div>

    <div ng-controller="SecondCtrl">
        <h2>{{name}}</h2>
        <input ng-model="someThing.x"/>             
    </div>
</body>
</html>

也在这里:https ://gist.github.com/3595424

于 2012-09-02T06:51:53.823 回答
33

如果您希望发出和广播事件以在控制器之间共享数据或调用函数,请查看此链接:并通过zbynour(以最高票数回答)检查答案。我引用他的回答!!!

如果 firstCtrl 的范围是 secondCtrl 范围的父级,则您的代码应该通过在 firstCtrl 中将 $emit 替换为 $broadcast 来工作:

function firstCtrl($scope){
    $scope.$broadcast('someEvent', [1,2,3]);
}

function secondCtrl($scope){
    $scope.$on('someEvent', function(event, mass) {console.log(mass)});
}

如果您的范围之间没有父子关系,您可以将 $rootScope 注入控制器并将事件广播到所有子范围(即 secondCtrl)。

function firstCtrl($rootScope){
    $rootScope.$broadcast('someEvent', [1,2,3]);
}

最后,当您需要将事件从子控制器向上分派到作用域时,您可以使用 $scope.$emit。如果 firstCtrl 的范围是 secondCtrl 范围的父级:

function firstCtrl($scope){
    $scope.$on('someEvent', function(event, data) { console.log(data); });
}

function secondCtrl($scope){
    $scope.$emit('someEvent', [1,2,3]);
}
于 2014-10-15T13:26:05.380 回答
24

还有两个小提琴:(非服务方法)

1) 对于父子控制器 - 使用$scope父控制器来发出/广播事件。 http://jsfiddle.net/laan_sachin/jnj6y/

2)$rootScope跨非相关控制器使用。 http://jsfiddle.net/VxafF/

于 2012-10-07T17:07:39.027 回答
17

实际上使用发射和广播是低效的,因为事件在范围层次结构中上下冒泡,这很容易降低复杂应用程序的性能瓶颈。

我建议使用服务。这是我最近在我的一个项目中实现它的方式 - https://gist.github.com/3384419

基本思想 - 将 pub-sub/event bus 注册为服务。然后在您需要订阅或发布事件/主题的任何地方注入该事件总线。

于 2012-08-18T04:32:39.167 回答
5

我也知道这种方式。

angular.element($('#__userProfile')).scope().close();

但我并没有用太多,因为我不喜欢在 Angular 代码中使用 jQuery 选择器。

于 2013-07-16T13:45:25.017 回答
3

有一种方法不依赖于服务,$broadcast或者$emit. 它并不适用于所有情况,但如果您有 2 个相关的控制器可以抽象为指令,那么您可以使用require指令定义中的选项。这很可能是 ngModel 和 ngForm 的通信方式。您可以使用它在嵌套或同一元素上的指令控制器之间进行通信。

对于父/子情况,使用如下:

<div parent-directive>
  <div inner-directive></div>
</div>

使其工作的要点:在父指令上,使用要调用的方法,您应该在this(而不是在$scope)上定义它们:

controller: function($scope) {
  this.publicMethodOnParentDirective = function() {
    // Do something
  }
}

在子指令定义中,您可以使用该require选项,以便将父控制器传递给链接函数(这样您就可以从scope子指令中调用函数。

require: '^parentDirective',
template: '<span ng-click="onClick()">Click on this to call parent directive</span>',
link: function link(scope, iElement, iAttrs, parentController) {
  scope.onClick = function() {
    parentController.publicMethodOnParentDirective();
  }
}

以上内容可见http://plnkr.co/edit/poeq460VmQER8Gl9w8Oz?p=preview

类似地使用同级指令,但两个指令都在同一个元素上:

<div directive1 directive2>
</div>

通过在 上创建方法来使用directive1

controller: function($scope) {
  this.publicMethod = function() {
    // Do something
  }
}

在指令 2 中,可以使用require导致将兄弟控制器传递给链接函数的选项来调用它:

require: 'directive1',
template: '<span ng-click="onClick()">Click on this to call sibling directive1</span>',
link: function link(scope, iElement, iAttrs, siblingController) {
  scope.onClick = function() {
    siblingController.publicMethod();
  }
}

这可以在http://plnkr.co/edit/MUD2snf9zvadfnDXq85w?p=preview看到。

这个的用途?

  • 父级:子元素需要向父级“注册”自己的任何情况。很像 ngModel 和 ngForm 之间的关系。这些可以添加某些可能影响模型的行为。您可能也有一些纯粹基于 DOM 的东西,其中父元素需要管理某些子元素的位置,比如管理或响应滚动。

  • 兄弟:允许指令修改其行为。ngModel 是经典案例,将解析器/验证添加到 ngModel 在输入上的使用。

于 2013-12-27T13:16:15.673 回答
3

我不知道这是否超出标准,但如果您将所有控制器都放在同一个文件中,那么您可以执行以下操作:

app = angular.module('dashboardBuzzAdmin', ['ngResource', 'ui.bootstrap']);

var indicatorsCtrl;
var perdiosCtrl;
var finesCtrl;

app.controller('IndicatorsCtrl', ['$scope', '$http', function ($scope, $http) {
  indicatorsCtrl = this;
  this.updateCharts = function () {
    finesCtrl.updateChart();
    periodsCtrl.updateChart();
  };
}]);

app.controller('periodsCtrl', ['$scope', '$http', function ($scope, $http) {
  periodsCtrl = this;
  this.updateChart = function() {...}
}]);

app.controller('FinesCtrl', ['$scope', '$http', function ($scope, $http) {
  finesCtrl = this;
  this.updateChart = function() {...}
}]);

如您所见,indicatorsCtrl 在调用 updateCharts 时正在调用其他两个控制器的 updateChart 函数。

于 2014-10-20T14:41:13.637 回答
2

您可以在父控制器(MessageCtrl)中注入“$controller”服务,然后使用以下方法实例化/注入子控制器(DateCtrl):
$scope.childController = $controller('childController', { $scope: $scope.$new() });

现在,您可以通过调用子控制器的方法来访问子控制器的数据,因为它是一项服务。
让我知道是否有任何问题。

于 2015-04-16T18:56:12.710 回答
1

以下是一种publish-subscribe与 Angular JS 无关的方法。

搜索参数控制器

//Note: Multiple entities publish the same event
regionButtonClicked: function () 
{
        EM.fireEvent('onSearchParamSelectedEvent', 'region');
},

plantButtonClicked: function () 
{
        EM.fireEvent('onSearchParamSelectedEvent', 'plant');
},

搜索选择控制器

//Note: It subscribes for the 'onSearchParamSelectedEvent' published by the Search Param Controller
localSubscribe: function () {
        EM.on('onSearchParamSelectedEvent', this.loadChoicesView, this);

});


loadChoicesView: function (e) {

        //Get the entity name from eData attribute which was set in the event manager
        var entity = $(e.target).attr('eData');

        console.log(entity);

        currentSelectedEntity = entity;
        if (entity == 'region') {
            $('.getvalue').hide();
            this.loadRegionsView();
            this.collapseEntities();
        }
        else if (entity == 'plant') {
            $('.getvalue').hide();
            this.loadPlantsView();
            this.collapseEntities();
        }


});

事件管理器

myBase.EventManager = {

    eventArray:new Array(),


    on: function(event, handler, exchangeId) {
        var idArray;
        if (this.eventArray[event] == null) {
            idArray = new Array();
        } else { 
            idArray = this.eventArray[event];
        }
        idArray.push(exchangeId);
        this.eventArray[event] = idArray;

        //Binding using jQuery
        $(exchangeId).bind(event, handler);
    },

    un: function(event, handler, exchangeId) {

        if (this.eventArray[event] != null) {
            var idArray = this.eventArray[event];
            idArray.pop(exchangeId);
            this.eventArray[event] = idArray;

            $(exchangeId).unbind(event, handler);
        }
    },

    fireEvent: function(event, info) {
        var ids = this.eventArray[event];

        for (idindex = 0; idindex < ids.length; idindex++) {
            if (ids[idindex]) {

                //Add attribute eData
                $(ids[idindex]).attr('eData', info);
                $(ids[idindex]).trigger(event);
            }
        }
    }
};

全球的

var EM = myBase.EventManager;
于 2014-02-21T14:10:28.390 回答
1

在 Angular 1.5 中,这可以通过执行以下操作来完成:

(function() {
  'use strict';

  angular
    .module('app')
    .component('parentComponent',{
      bindings: {},
      templateUrl: '/templates/products/product.html',
      controller: 'ProductCtrl as vm'
    });

  angular
    .module('app')
    .controller('ProductCtrl', ProductCtrl);

  function ProductCtrl() {
    var vm = this;
    vm.openAccordion = false;

    // Capture stuff from each of the product forms
    vm.productForms = [{}];

    vm.addNewForm = function() {
      vm.productForms.push({});
    }
  }

}());

这是父组件。在此,我创建了一个将另一个对象推入我的productForms数组的函数 - 注意 - 这只是我的示例,这个函数实际上可以是任何东西。

现在我们可以创建另一个组件来使用require

(function() {
  'use strict';

  angular
    .module('app')
    .component('childComponent', {
      bindings: {},
      require: {
        parent: '^parentComponent'
      },
      templateUrl: '/templates/products/product-form.html',
      controller: 'ProductFormCtrl as vm'
    });

  angular
    .module('app')
    .controller('ProductFormCtrl', ProductFormCtrl);

  function ProductFormCtrl() {
    var vm = this;

    // Initialization - make use of the parent controllers function
    vm.$onInit = function() {
      vm.addNewForm = vm.parent.addNewForm;
    };  
  }

}());

在这里,子组件创建对父组件函数的引用,addNewForm然后可以将其绑定到 HTML 并像任何其他函数一样调用。

于 2016-03-23T17:10:13.973 回答
0

您可以使用$controllerAngularJS 提供的服务。

angular.module('app',[]).controller('DateCtrl', ['$scope', function($scope){
  $scope.currentDate = function(){
    return "The current date is: " + new Date().toString(); 
  }
}]);

angular.module('app').controller('MessageCtrl', ['$scope', function($scope){

  angular.extend(this, $controller('DateCtrl', {
      $scope: $scope
  }));

  $scope.messageWithDate = function(message){
    return "'"+ message + "', " + $scope.currentDate;
  }

  $scope.action2 = function(){
    console.log('Overridden in ChildCtrl action2');
  }

}]);
于 2020-06-24T10:14:39.580 回答