search

Home  >  Q&A  >  body text

angular.js - angular $scope.$on receives events and executes them repeatedly

Pass values ​​between

angular controller through events

Every time the page refreshes the route, the view ui-view will be refreshed,

Binded controller

angular.controller('listCtrl',[])

will be reloaded (because I bound the listCtrl controller to the label in the view)

controller within

$scope.$on('testData',function(ev,data){
 //
})

will record the number of times listCtrl is reloaded. When the testData event is received, $on will be executed repeatedly for the corresponding number of times.

I only want testData to be executed once, what should I do

给我你的怀抱给我你的怀抱2799 days ago1024

reply all(1)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-15 17:07:58

    Thank you for the invitation, write a service or hang a global variable on $rootScope

    if(!$rootScope.isInvoked) {
        var unbindHandler = $scope.$on('testData', function(evt, data) {
            //执行完成后就把该事件解绑 
            unbindHandler();
            $rootScope.isInvoked = true;
        });
    }

    Of course, regarding event subscription and sending, if it is not a situation like routing that requires notification to all scopes, it is recommended not to use the event mechanism that comes with AngularJS. It is recommended to write an EventBus service to handle it yourself. Because the event mechanism of AngularJS needs to traverse the entire scope tree, the performance is average.

    Recommend an internal summary of our team:
    https://github.com/ShuyunXIAN...

    reply
    0
  • Cancelreply