Search code examples
angularjsangularjs-directiveangularjs-serviceangular-translate

AngularJS: Execute function of directive on pageload


This is my directive that handles popovers. I do use angular-translate to translate the text in different languages:

angular.module('c2gyoApp')
  .directive('tariffPopover', [
    '$translate', 
    '$rootScope', 
    function ($translate, $rootScope) {
return {
  restrict: 'A',
  transclude: true,
  scope: {
    translateText: '@tariffPopover'
  },
  template:
    '<span ng-transclude></span>' +
    '&nbsp;' +
    '<span popover-placement="right" ' +
    '      uib-popover-html="text" ' +
    '      popover-trigger="mouseenter" ' +
    '      class="fa fa-info-circle">' +
    '</span>',
  controller: function ($scope) {
    $translate($scope.translateText).then(function (translatedText) {
      $scope.text = translatedText;
    });

    $rootScope.$on('$translateChangeSuccess', function () {
      $translate($scope.translateText).then(function (translatedText) {
        $scope.text = translatedText;
      });
    });

  }
};
}]);

The translation gets executed when the language changes with $rootScope.$on('$translateChangeSuccess'). However this does not execute when the page loads, so I added the lines to translate the text again in the controller:

  controller: function ($scope) {
    $translate($scope.translateText).then(function (translatedText) {
      $scope.text = translatedText;
    });

    $rootScope.$on('$translateChangeSuccess', function () {
      $translate($scope.translateText).then(function (translatedText) {
        $scope.text = translatedText;
      });
    });

Is there a way to execute the translation on pageload without having code duplication?


Solution

  • If all you want to do is avoid a copy-paste, then I think it is a better object-oriented practice to wrap the duplicated code in a named function rather than using an anonymous function. This way it can be reused.

    controller: function ($scope) {
    
      var translate = function(){
         $translate($scope.translateText).then(function (translatedText) {
             $scope.text = translatedText;
        });
      }
    
      $rootScope.$on('$translateChangeSuccess', translate);
    
      //execute the translation when the controller loads
      translate();
    }