Translating during config phase (using angular-translate)

 ̄綄美尐妖づ 提交于 2020-01-10 05:29:06

问题


I'm developing the i18n part of my Angular web app, and I'd like to use angular-translate in my config phase.

I defined some data that I'd like to translate:

.state('app.tracking', {
    url: '/:IdentityIdentifier',
    params:{
        IdentityIdentifier: {squash: false, value: null}
    },
    templateUrl: 'views/pages/tracking.html',
    data : { title: $filter('translate')('tracking.tracking.TITLE') },
    resolve: load([], function(){ return loadGoogleMaps(); })
})

Here's my config declaration:

.config(
  [          '$stateProvider', '$urlRouterProvider', '$locationProvider', 'MODULE_CONFIG', '$httpProvider', '$filter',
    function ($stateProvider,   $urlRouterProvider,   $locationProvider,   MODULE_CONFIG,   $httpProvider,   $filter) {

The error I get is classic: Error: [$injector:unpr] Unknown provider: $filter

I'm aware I can't use services in config phase, only providers, but is there a solution to my problem?

EDIT: My problem has been solved by assigning the key 'tracking.tracking.TITLE' to my data.title variable, then translating it using translate directive in my markup.


回答1:


Yes, like mentioned in the EDIT to the question: applying the filter in the markup is obviously the easiest solution.

Besides that, if one would really want to access services in config phase, then read on:

It is technically not possible in Angular <= 1.4.

Starting from Angular v1.5 (current rc version is 1.5.0-rc.0) it seems to be possible, although I cannot recommend to do so, because the config phase should just be the place where the services are configured before they're used for the first time.

This is the change that made the following possible (link to angular.js repo at github) (it was only made to allow decorating $injector).

Now, here comes the example: http://codepen.io/NicBright/pen/PZJBPP?editors=101

JS part:

(function() {
  var result;

angular.module('myApp', [])
  .config(function($injectorProvider) {
    result = $injectorProvider.$get().get('myService').getSomething();
  })
  .factory('myService', function() {
    return { getSomething: function() { return 'it works!'; }}
  })
  .controller("MainCtrl", function($scope) {
    $scope.result = result;
  })

})();

HTML part:

<div ng-app="myApp" ng-controller="MainCtrl">
  result: {{ result }}
</div>


来源:https://stackoverflow.com/questions/34832353/translating-during-config-phase-using-angular-translate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!