hussain hussain - 1 month ago 15
AngularJS Question

angular $broadcast event is not firing?

I want to send data from parent to child controller but its not firing event from parent controller its been hours i am scratching my head find the problem but i failed so decided to ask help on stackoverflow, Any idea what is wrong in below code ?

ParentCtrl.js

angular.module('angularModelerApp')
.controller('ModelerCtrl', ['$scope', '$state','$log', 'toastr', 'FileSaver', 'Blob', '$uibModal', '$rootScope', '$timeout', function($scope, $state, $log, toastr, FileSaver, Blob, $uibModal, $rootScope, $timeout) {

$scope.deleteXml = function(id, toast) {
var id = $scope.diagramObj._id;
$scope.modalInstance = $uibModal.open({
templateUrl: 'app/modeler/modelerDialog/modelerDialog.html',
controller: 'ModelerDialogCtrl'
});
$timeout(function() {
$rootScope.$broadcast('delete-diagram', {
id: id
});
});
}
});


childCtrl.js

angular.module('angularModelerApp')
.controller('ModelerDialogCtrl', function ($scope, $uibModalInstance,$log,diagramService,$rootScope) {

$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
$scope.$on('delete-diagram',function(e,data){
console.log('in $on',data);
});

Answer

Why dont you pass the id when you open the modal such as:

$scope.modalInstance = $uibModal.open({
  templateUrl: 'app/modeler/modelerDialog/modelerDialog.html',
  controller: 'ModelerDialogCtrl',
  resolve: {
    item: function() {
      return $scope.diagramObj._id
    }
   }
 });

Fetch it in the child component in this way: angular.module('angularModelerApp')

 .controller('ModelerDialogCtrl', function ($scope, $uibModalInstance,$log,diagramService,$rootScope) {

    $scope.cancel = function() {
      $uibModalInstance.dismiss('cancel');
    };
    $scope.$on('delete-diagram',function(e,data){
      console.log('in $on',data);
    });


    $uibModalInstance.result.then(function (data) {
       console.log(data);
    })
}