[英]How to communicate parent controller in angularjs using $emit
I am trying to pass child value to parent textbox.我正在尝试将子值传递给父文本框。 Below is Parent and child controller :下面是父子控制器:
var myApp = angular.module('myApp',[]);
myApp.controller("ParentController",
function($scope,$rootScope) {
$scope.name = null;
$scope.$on('someEvent', function(event,data){
alert(JSON.stringify(data));
$scope.name = data;
});
});
myApp.controller("ChildController",
function($scope,$rootScope) {
$scope.name2 = {name: "MyCtrl"};
$scope.emit = function(){
$rootScope.$emit('someEvent', $scope.name2);
};
});
Here is HTML code:这是 HTML 代码:
<div ng-controller="ParentController">
<input type="text" ng-model="name.name"/>
<div ng-controller="ChildController">
<input type="text" ng-model="name2.name"/>
<button ng-click="emit()">
Emit event
</button>
</div>
</div>;
alert message is not working??警报消息不起作用?
You should be calling $emit
on the $scope
, not the $rootScope
.您应该在$scope
上调用$emit
,而不是$rootScope
。 $emit
is intended to propagate an event upwards, from a child controller to a parent. $emit
旨在向上传播事件,从子控制器到父控制器。 If you wanted to go the other direction, you could use $broadcast
, to propagate an event down from a parent to a child.如果你想走另一个方向,你可以使用$broadcast
,将事件从父级向下传播到子级。 Here is a simple example, that will randomly generate a number in a child controller, and pass that up to the parent using $emit
.这是一个简单的示例,它将在子控制器中随机生成一个数字,并使用$emit
将其传递给父控制器。
var app = angular.module('plunker', []);
app.controller('ParentCtrl', function($scope) {
$scope.$on('changeVar', function(e, nv) {
$scope.parentVar = nv;
});
$scope.parentVar = 5;
});
app.controller('ChildCtrl', function($scope) {
$scope.emitToParent = function() {
var newVal = Math.floor(Math.random() * 100) + 1;
$scope.$emit('changeVar', newVal);
};
});
See the following plunker for a working example: http://plnkr.co/edit/3E5tZgOs8sCXvBRdVq4p有关工作示例,请参阅以下 plunker: http ://plnkr.co/edit/3E5tZgOs8sCXvBRdVq4p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.