AngularJS: 在页面加载时执行指令的功能

AngularJS: Execute function of directive on pageload

这是我处理弹出窗口的指令。我确实使用 angular-translate 将文本翻译成不同的语言:

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;
      });
    });

  }
};
}]);

当语言随着 $rootScope.$on('$translateChangeSuccess') 发生变化时,将执行翻译。但是,这不会在页面加载时执行,所以我在控制器中添加了以下行以再次翻译文本:

  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;
      });
    });

有没有办法在没有代码重复的情况下在页面加载时执行翻译?

尝试替换

$translateChangeSuccess

$locationChangeSuccess使其在page/location改变时生效。

也可以使用$viewContentLoaded,如果你想在页面内容加载后得到它。

希望对您有所帮助..!

如果您只想避免 copy-paste,那么我认为 object-oriented 将重复代码包装在命名函数中而不是使用匿名函数是更好的做法。这样它就可以重复使用。

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();
}