AngularJS directive $destroy

后端 未结 1 1436
时光说笑
时光说笑 2021-02-03 19:29

I have an angular app setup with ng-view. In one view, in addition to the view itself, there is also a component inside that view that is dynamically loaded. This c

相关标签:
1条回答
  • 2021-02-03 19:56

    The i18n example you provided would work if you only ever used it once.

    I don't think you should be doing the event binding inside the compile function. You can do it inside the link function instead:

    angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
      return {
        restrict: 'EAC',
        link: function(scope, element, attrs) {
          var cleanup;
          var originalText = element.text();
          element.text(LocaleService.getTranslation(originalText, attrs.locale));
          cleanup = $rootScope.$on('locale-changed', function(locale) {
            element.text(LocaleService.getTranslation(originalText, attrs.locale || locale));
          });
          scope.$on('$destroy', function() {
            console.log("destroy");
            cleanup();
          });
        }
      };
    }]);
    

    Alternatively, you could bind the event on the child scope itself, and use $broadcast on the $rootScope to trigger it. That way the event will automatically be garbage collected when the scope is destroyed:

    angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
      return {
        restrict: 'EAC',
        link: function(scope, element, attrs) {
          var originalText = element.text();
          setElText();
          function setElText(locale){
            element.text(LocaleService.getTranslation(originalText, attrs.locale || locale));
          }
          scope.$on('locale-changed', setElText);
        }
      };
    }]);
    
    $rootScope.$broadcast('locale-change', 'en-AU');
    
    0 讨论(0)
提交回复
热议问题