Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

angularjs - Translating during config phase (using angular-translate)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...