Search code examples
angularjsangularjs-rootscope

Angular js using $rootScope in ng-src script on refresh fails


I'm creating a project with internationalization, where labels will be in /conf/lang/lang_{{lang}}/labels.js which will included in index.html. lang - rootscope variable setting in app.run(). Index.html

 <script ng-src="{{labelUrl}}"></script>

app.js - run()

$rootScope.$on('$locationChangeStart', function (event, next, current) 
    {

        if($cookieStore.get("config_details") != undefined)
        {
            $rootScope.language = $cookieStore.get("config_details").language;
        }
        else
        {
            $rootScope.language = 'english';
        }
        $rootScope.labelUrl = "conf/lang/lang_"+$rootScope.language+"/labels.js";
})

This script file is loading correctly on url changing but when refresh manually the $rootscope value destroys and the script file is loading after html content is loaded. Somebody help me to resolve this!!!


Solution

  • Yes when you try to reload a page everything will be destroyed. Look at this

        var myApp = angular.module('myApp', ['ngCookies']);
    
        myApp.controller('MainController', ['$scope', '$rootScope', '$cookies', '$timeout', function($scope, $rootScope, $cookies, $timeout) {
          if ($cookies.get('lang')) {
            $scope.debug = "Browser has got cookies";
            $rootScope.language = $cookies.get('lang');
          } else {
            $scope.debug = "Browser does not have cookies";
            $timeout(function() {
              $cookies.put('lang', 'en');
              $rootScope.language = 'en';
              $scope.debug = "Browser has got cookies";
            }, 2000);
          }
        }]);
    

    Example

    Try angular-translate