一个AngularJS控制器可以调用另一个吗?

本文翻译自:Can one AngularJS controller call another?

Is it possible to have one controller use another? 一个控制器可以使用另一个控制器吗?

For example: 例如:

This HTML document simply prints a message delivered by the MessageCtrl controller in the messageCtrl.js file. 该HTML文档仅在messageCtrl.js文件中打印由MessageCtrl控制器传递的MessageCtrl

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

The controller file contains the following code: 控制器文件包含以下代码:

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

Which simply prints the current date; 它只是打印当前日期;

If I were to add another controller, DateCtrl which handed the date in a specific format back to MessageCtrl , how would one go about doing this? 如果要添加另一个控制器DateCtrl ,它将特定格式的日期交还给MessageCtrl ,那该怎么办呢? The DI framework seems to be concerned with XmlHttpRequests and accessing services. DI框架似乎与XmlHttpRequests和访问服务有关。


#1楼

参考:https://stackoom.com/question/czdv/一个AngularJS控制器可以调用另一个吗


#2楼

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

Also watch the following video: Communicating Between Controllers 另请观看以下视频: 控制器之间的通信

Html: 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: 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'];

#3楼

Actually using emit and broadcast is inefficient because the event bubbles up and down the scope hierarchy which can easily degrade into performance bottlement for a complex application. 实际上,使用发射和广播效率不高,因为事件在作用域层次结构中上下起泡,对于复杂的应用程序而言,事件层次结构很容易降级为性能瓶颈。

I would suggest using a service. 我建议使用服务。 Here is how I recently implemented it in one of my projects - https://gist.github.com/3384419 . 这是我最近在我的一个项目-https: //gist.github.com/3384419中实现它的方式。

Basic idea - register a pub-sub/event bus as a service. 基本思想-将pub-sub / event总线注册为服务。 Then inject that event bus where ever you need to subscribe or publish events/topics. 然后将事件总线注入您需要订阅或发布事件/主题的地方。


#4楼

Here is a one-page example of two controllers sharing service data: 这是两个控制器共享服务数据的一页示例:

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

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


#5楼

Two more fiddles: (Non service approach) 另外两个小提琴:(非服务方法)

1) For Parent- Child controller - Using $scope of parent controller to emit/broadcast events. 1)对于父子控制器-使用父控制器的$scope发出/广播事件。 http://jsfiddle.net/laan_sachin/jnj6y/ http://jsfiddle.net/laan_sachin/jnj6y/

2) Using $rootScope across non-related controllers. 2)在不相关的控制器之间使用$rootScope http://jsfiddle.net/VxafF/ http://jsfiddle.net/VxafF/


#6楼

I also know of this way. 我也知道这种方式。

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

But I don't use it too much, because I don't like to use jQuery selectors in angular code. 但是我并没有使用太多,因为我不喜欢在角度代码中使用jQuery选择器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值