Search code examples
angularjsangularjs-scopeionic-frameworkangular-translate

Angular translate inside service


I am struggling with angular translate for my ionic app. The thing is that I have a service with data to share between views but I need to translate this data. Unfortunately I just see blank screen without any errors in console.

I would appreciate if someone could help if there is something wrong with that code (I use useStaticFilesLoader):

app.service('customService', function($q, $rootScope, $filter, $translate) {

    $rootScope.$on('$translateChangeSuccess', function () {     
        var $translate = $filter('translate');                      

    return {
    items: [
      {
        id: '1',        
        title:$translate('TITLE');
      }
    ]
],
    getItems: function() {
      return this.items;
    },
    getItem: function(itemId) {
      var dfd = $q.defer();
      this.items.forEach(function(item) {
        if (item.id === itemId) dfd.resolve(item);
      });

      return dfd.promise;
    }

 };
});
});

Solution

  • Try something like this:

    app.factory('customService', function($rootScope, $translate) {
        var items = [],
            updateItems = function() {
                items.length = 0;
                $translate('TITLE').then(function(title) {
                    items.push({
                        id: '1',
                        title: title;
                    });
                });
            };
        updateItems();
        $rootScope.$on('$translateChangeSuccess', updateItems);
        return {
            items: items,
            getItem: function(itemId) {
                var result;
                items.forEach(function(item) {
                    if (item.id === itemId) {
                        result = item;
                    }
                });
                return result;
            }
        }
    });