How to pass data from parent to child controller using angular $broadcast?

时间:2016-10-20 19:55:36

标签: javascript angularjs

I want to pass id argument to child controller using angular $broadcast but with below code i am not able to achieve that task any idea what is implemented wrong ?

ParentCtrl.js

 $scope.deleteXml = function(id, toast) {
     var id = $scope.diagramObj._id;
     var modalInstance = buildModal(null, 'delete');
     modalInstance.result.then(function(user) {
         //$scope.users.push(user);
     }, function() {
         //$log.info('Modal dismissed at: ' + new Date());
     });
     $rootScope.$broadcast('delete-diagram', id);
     $scope.refreshDiagrams;

 }

ChildCtrl.js

$rootScope.$on('delete-diagram', function(event, id) {
                console.log(id);
             });

1 个答案:

答案 0 :(得分:0)

Your approach is correct. However you also need to destroy $rootScope event.

Ex.

    $rootScope.$broadcast('myEvent',$scope.data);

   var customeEventListener = $rootScope.$on('myEvent', function(event, data) {

  }
  $scope.$on('$destroy', function() {
        customeEventListener();
  });

or,

It is better to use $scope.$on as listeners on $scope are destroyed automatically i.e. as soon as $scope is destroyed.

$scope.$on('myEvent', function(event, data) {}