0

First time when I click on the link to open the dialog, it is opening only one time. But from the second time, it is opening two times, four times , eight times on second, third, fourth click respectively. Why is it opening multiple times?

Html code: header.html

<li><a href data-ng-click="chatBotFunction()" chat-bot>Chat</a></li>

JS code: headerCtrl.js

$scope.chatBotFunction = function() {
    $rootScope.$emit("CallChatMethod",{});
}

chatCtrl.js

$rootScope.$on("CallChatMethod", function(){
    $scope.openChatBox();
});

$scope.openChatBox = function() {
    ngDialog.openConfirm({
        template: 'modules/main/views/chatBot.html',
        controller: 'chatCtrl',
        closeByDocument: false,
        closeByEscape: false,
        showClose: false,
        scope: $scope 
    }).then(

    );  
};

Someone please help me solve this. Thanks in advance.

Kavipriya
  • 441
  • 4
  • 17

2 Answers2

1

The problem was, if you use $rootScope.$on the respective controller will not destroy even when you navigate to other pages. So try with $scope.$on

$scope.$on("CallChatMethod", function(){
    $scope.openChatBox();
});

$scope.$broadcast is for when publishing from parent to child
$scope.$emit is for when publishing from child to parent

Let me knw if you still face problem.

Srigar
  • 1,648
  • 3
  • 14
  • 28
  • I fear it may not work. I believe $rootScope.$emit only lets other $rootScope listeners catch it as mentioned http://stackoverflow.com/questions/26752030/rootscope-broadcast-vs-scope-emit – Gopinath Shiva Apr 10 '17 at 10:50
  • Try it.. surely it will work. All are works under prototype concept only – Srigar Apr 10 '17 at 10:52
  • Can u check this fiddle https://jsfiddle.net/U3pVM/31464/ . Not working when used with $scope.$emit – Gopinath Shiva Apr 10 '17 at 10:57
  • 1
    Use $scope.$broadcast, because u publishing from parent to child. U have to use emit only when u publish child to parent. check this link jsfiddle.net/U3pVM/31467/ – Srigar Apr 10 '17 at 11:11
  • It works when i use `$scope.$broadcast`. Thanks. And please include that in the answer , it will be useful for others :) – Kavipriya Apr 10 '17 at 11:29
  • Sure ill add. If it is works kindly accept the answer. – Srigar Apr 10 '17 at 11:32
0

You need to remove the listener on scope destroy event

var callChatListener = $rootScope.$on("CallChatMethod", function(){
   $scope.openChatBox();
});

Below code will remove listener from $rootscope

$scope.$on("$destroy", function(){
   callChatListener(); 
});
Aravind Sivam
  • 1,089
  • 8
  • 23