简体   繁体   中英

$rootScope.$broadcast Issue

I'm trying to send a broadcast event. So, that are my needed files:

html:

<ion-list>
  <ion-item ng-repeat="item in items" ng-click="selectItem(item)" href="#/app/item/{{item.id}}">
    {{item.name}}
  </ion-item>
</ion-list>

So, when I click an item selectItem(item) is called on the controller:

controllers.js:

.controller('SelectItemCtrl', function($rootScope, $scope) {
  $scope.items = // define my items list;
  $scope.selectItem = function(selectedItem) {
    console.log("Item was selected");
    $rootScope.$broadcast('new-selected-item', {selectedItem});
    console.log('Message sent');
  }
})
.controller('DetailItemCtrl', function($rootScope, $scope) {
  console.log('DetailItemCtrl started');
  $scope.$on('new-selected-item', function(event, args) { 
    console.log(Message received);
    console.log(args);
  }
});

Of course my app.js links that url to the controller:

app.js:

.state('app.item-detail', {
  url: '/item/:itemId',
  views: {
    'menuContent': {
      templateUrl: 'templates/detail.html',
      controller: 'DetailItemCtrl'
    }
  }
})

So, when I select an item, my console log is:

Message sent
DetailItemCtrl

I don't know why I cannot get the event.

When your trigger the ng-click the controller is no longer active so any actions called from it( selectItem(item)) will not get fired. If you need something to hold state and communicate between controllers you should use a service. https://docs.angularjs.org/guide/services

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM