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

例如:

这个HTML文档只是打印MessageCtrl控制器在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框架似乎与xmlhttprequest和访问服务有关。


当前回答

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

最好的可能是共享服务:

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

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

其他回答

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

<!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

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

现在您可以通过调用子控制器的方法来访问数据,因为它是一个服务。 如果有任何问题请告诉我。

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

对于父母/孩子的情况,使用方法如下:

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

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

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

在子指令定义上,你可以使用require选项,这样父控制器就被传递给了链接函数(这样你就可以从子指令的作用域调用它上的函数)。

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
  }
}

在directive2中,可以使用require选项调用,这将导致siblingController被传递给link函数:

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上看到。

它的用途是什么?

Parent: Any case where child elements need to "register" themselves with a parent. Much like the relationship between ngModel and ngForm. These can add certain behaviour that can affects models. You might have something purely DOM based as well, where a parent element needs to manage the positions of certain children, say to manage or react to scrolling. Sibling: allowing a directive to have its behaviour modified. ngModel is the classic case, to add parsers / validation to ngModel use on inputs.

我也知道这条路。

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

但我不太使用它,因为我不喜欢在angular代码中使用jQuery选择器。

我不知道这是否超出了标准,但如果你把所有的控制器都放在同一个文件上,那么你可以这样做:

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() {...}
}]);

正如你所看到的,当调用updateCharts时,indicatorsCtrl正在调用其他两个控制器的updateChart函数。