Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to communicate parent controller in angularjs using $emit

Tags:

html

angularjs

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:

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

like image 329
Rishi Avatar asked Mar 10 '26 04:03

Rishi


1 Answers

You should be calling $emit on the $scope, not the $rootScope. $emit is intended to propagate an event upwards, from a child controller to a parent. If you wanted to go the other direction, you could use $broadcast, to propagate an event down from a parent to a child. Here is a simple example, that will randomly generate a number in a child controller, and pass that up to the parent using $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

like image 196
james00794 Avatar answered Mar 12 '26 22:03

james00794



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!