0

I have a button where I am passing the ng-model value as a parameter to its ng-click function, Now after this ng-click function executes, I would like to send that ng-model value to another controller, how can I do this using angular?

Is there a way to do this?

krishna teja
  • 159
  • 2
  • 9

3 Answers3

1

There are many ways to communicate between controllers.

  1. use $broadcast like mentioned in other comments, or
  2. use $emit

Something like this...

function Controller1($scope) 
{
    $scope.$on('myEvent', function(event, args) {
        // do the event
    });
  // another controller, directive
}

function Controller2($scope) 
{
  $scope.$emit('myEvent', args);
}
0

1.In first Controller, you can do:

$rootScope.$broadcast('eventName', value);

and listen to the event in second Controller:

$scope.$on('eventName', function (event, value) {//your code});

2.In first controller assign the values to the $rootScope variable then access from the other controller.for example in first controller

$rootScope.TestValue="10";

in second controller

$scope.receiveValue=$rootScope.TestValue;

3.AngularJS- How to pass data from one controller to another on ng-click()?

-2

Use angular service to communicate between 2 controller. Watch this Video

Yes $broadcast will work for you.

Here are some essential parts:

  1. Create service that implements message bus functionality (e.g. $scope instance)
  2. Inject service to both controllers
  3. $broadcast() event from one controller
  4. subscribe to event with $on() in another

Example:

HTML

<div ng-controller="ctrl1 as ctrl1">
  <button ng-click="ctrl1.hello()">Say hello</button>
</div>
<div ng-controller="ctrl2 as ctrl2">{{ctrl2.messages}}</div>

JavaScript

angular.module('app', [])
.service('messageBus', ['$rootScope', function($rootScope) {
  return $rootScope.$new();
}])
.controller('ctrl1', ['messageBus', function(messageBus) {
  this.hello = function() {
    messageBus.$broadcast('hello', 'Hi! '); // <= send message
  }
}])
.controller('ctrl2', ['messageBus', function(messageBus) {
  var ctrl2 = this;
  this.messages = '';
  console.log(messageBus.mb)
  messageBus.$on('hello', function(evt, msg) { // <= receive message
    ctrl2.messages += msg;
  });
}]);
Vadim
  • 8,701
  • 4
  • 43
  • 50
Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93