是否可以让一个控制器使用另一个控制器?
例如:
此 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 框架似乎与 XmlHttpRequests
和访问服务有关。
控制器之间有多种通信方式。
最好的可能是共享服务:
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);
}
在这两种情况下,您也可以与任何指令进行通信。
看到这个小提琴:http://jsfiddle.net/simpulton/XqDxG/
另请观看以下视频:Communicating Between Controllers
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'];
如果您想将一个控制器调用到另一个控制器中,有四种方法可用
$rootScope.$emit() 和 $rootScope.$broadcast() 如果 Second controller 是 child,你可以使用 Parent child 通信。使用服务类型的 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 上显示了它们自己的值,当您单击文本时,您将相应地在控制台中获取值。如果单击父控制器跨度,浏览器将控制子控制器的值,反之亦然。
这是两个控制器共享服务数据的单页示例:
<!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
theService
更新 thing.x
,那么该更改会自动传播到 FirstCtrl
和 SecondCtrl
中的 <input>s,对吗?还可以通过两个 中的任何一个直接更改 thing.x
(对吗?)。
如果您希望发射 &广播事件以在控制器之间共享数据或调用函数,请查看此link:并检查 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]);
}
还有两个小提琴:(非服务方法)
1) 对于父子控制器 - 使用父控制器的 $scope
来发出/广播事件。 http://jsfiddle.net/laan_sachin/jnj6y/
2) 在不相关的控制器中使用 $rootScope
。 http://jsfiddle.net/VxafF/
实际上使用发射和广播是低效的,因为事件在范围层次结构中上下冒泡,这很容易降低复杂应用程序的性能瓶颈。
我建议使用服务。以下是我最近在我的一个项目中实现它的方式 - https://gist.github.com/3384419。
基本思想 - 将 pub-sub/event bus 注册为服务。然后在您需要订阅或发布事件/主题的任何地方注入该事件总线。
我也知道这种方式。
angular.element($('#__userProfile')).scope().close();
但我并没有用太多,因为我不喜欢在 Angular 代码中使用 jQuery 选择器。
有一种方法不依赖于服务,$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 在输入上的使用。
我不知道这是否超出标准,但如果您将所有控制器都放在同一个文件中,那么您可以执行以下操作:
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 函数。
您可以在父控制器 (MessageCtrl) 中注入“$controller”服务,然后使用以下方法实例化/注入子控制器 (DateCtrl):
$scope.childController = $controller('childController', { $scope: $scope.$new() });
现在,您可以通过调用子控制器的方法来访问子控制器的数据,因为它是一项服务。让我知道是否有任何问题。
以下是与 Angular JS 无关的 publish-subscribe
方法。
搜索参数控制器
//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;
在 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 并像任何其他函数一样调用。
您可以使用 AngularJS 提供的 $controller
服务。
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');
}
}]);
不定期副业成功案例分享