1

I´m trying to do something like this in AngularJS:

.factory('TranslationService', function($location, $rootScope, $routeParams, $translate, $window, tmhDynamicLocale, 
                                            LocationService, MetaService) {
      return {
        translate: function(language, translateUrlName) {

            $translate.uses(language).then(function() {

                this.translateUrl(language, translateUrlName);
            });
         },
         translateUrl: function(language, translateUrlName) {
            // do whatever
        }
      };     
    })

But I don´t know why I´m getting this error:

TypeError: Cannot read property 'translateUrl' of undefined
    at services.js:1117
    at deferred.promise.then.wrappedCallback (angular.js:6846)
    at angular.js:6883
    at Object.$get.Scope.$eval (angular.js:8057)
    at Object.$get.Scope.$digest (angular.js:7922)
    at Object.$get.Scope.$apply (angular.js:8143)
    at done (angular.js:9170)
    at completeRequest (angular.js:9333)
    at XMLHttpRequest.xhr.onreadystatechange (angular.js:9303)angular.js:5754 (anonymous function)angular.js:4846 $getangular.js:6848 deferred.promise.then.wrappedCallbackangular.js:6883 (anonymous function)angular.js:8057 $get.Scope.$evalangular.js:7922 $get.Scope.$digestangular.js:8143 $get.Scope.$applyangular.js:9170 doneangular.js:9333 completeRequestangular.js:9303 xhr.onreadystatechange

If I just move the call this.translateUrl(language, translateUrlName); outside of translate: function(language, translateUrlName) { then it works, but I don´t get the correct behavior.

2 Answers 2

2

The standard trap with closures and this in Javascript. Do:

  return {
    translate: function(language, translateUrlName) {
        var self = this;

        $translate.uses(language).then(function() {
            self.translateUrl(language, translateUrlName);
        });
     },
     translateUrl: function(language, translateUrlName) {
        // do whatever
    }
  };     
})
Sign up to request clarification or add additional context in comments.

Comments

1

change the code to

.factory('TranslationService', function($location, $rootScope, $routeParams, 
         $translate, $window, tmhDynamicLocale, LocationService, MetaService) {

    function translateUrl(language, translateUrlName) {
            // do whatever
        }

      function translate(language, translateUrlName) {

            $translate.uses(language).then(function() {

                translateUrl(language, translateUrlName);
            });
         }

      return {
        translate: translate,
         translateUrl: translateUrl
      };     
    })

its better to use named functions, as they do help in debugging...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.