Using $emit in angular 1.5 component

后端 未结 3 468
悲&欢浪女
悲&欢浪女 2021-01-04 03:35

I am using angular 1.5 component and need to call function in parent controller from when $emit in child component. How we can do this?

Example:

(fu         


        
3条回答
  •  情书的邮戳
    2021-01-04 03:53

    You can do it like this using $rootScope. It works fine in my case -

    child component:

    (function (angular) {
     'use strict';
    
     childController.$inject = ['$rootScope'];
    
     function childController($rootScope) {
       $rootScope.$emit('myEvent',$scope.data)
     }
    })(angular);
    

    Parent Component:

    (function (angular) {
     'use strict';
    
     controllerName.$inject = ['$rootScope'];
    
     function controllerName($rootScope) {
       var _this = this;
       function toBeCalledOnEmit() {//some code}
       var vm = {
          toBeCalledOnEmit: toBeCalledOnEmit
       }
       $rootScope.$on('myEvent', function(event, msg) {
         toBeCalledOnEmit();
       });
       angular.extend(_this, vm);
     }
    })(angular);
    

提交回复
热议问题