1

I am new to angular. Am having two controller. One controller have a button. That button's click event wrote in another controller's script. How to make fire the click event. Please help. Thank in advance.

controller==> A
<button ng-click="click()"></button>



<script>
controller ==> B
$scope.click = function()
{
alert("hai");
}
<script>

My doubt explains above sample code.

  • 1
    You can use service to call the same function from both controller when click – Avihay m Mar 30 '17 at 13:08
  • Possible duplicate of [What's the correct way to communicate between controllers in AngularJS?](http://stackoverflow.com/questions/11252780/whats-the-correct-way-to-communicate-between-controllers-in-angularjs) – Sachila Ranawaka Mar 30 '17 at 13:08

1 Answers1

0

You can do it by using angular events that is $emit and $broadcast.

First we call a function from one controller.

var myApp = angular.module('sample', []);
myApp.controller('firstCtrl', function($scope) {
    $scope.sum = function() {
        $scope.$emit('sumTwoNumber', [1, 2]);
    };
});
myApp.controller('secondCtrl', function($scope) {
    $scope.$on('sumTwoNumber', function(e, data) {
        var sum = 0;
        for (var a = 0; a < data.length; a++) {
            sum = sum + data[a];
        }
        console.log('event working', sum);

    });
});

You can also use $rootScope in place of $scope. Use your controller accordingly.