Cdok Cdok - 5 months ago 19
AngularJS Question

AngularJS / UI Router - Locale in State URL / TemplateURL

What I'm trying to accomplish is to set a

$scope
variable to the state parameters,

.state('form', {
url: '/' + locale + '/form',
templateUrl: locale + '/form.html',
controller: 'formController'
})


Currently I'm just using a variable

var locale


However I want the URL's to dynamically change if the

$scope.locale


changes. For example, if the user selects English, then the scope will change to

$scope.locale = 'en';


I want this to also reflect in the states / URL, and bring the user to the appropriate language page. I guess I'm trying to do something like this:

.state('form', {
url: '/' + $scope.locale + '/form',
templateUrl: $scope.locale + '/form.html',
controller: 'formController'
})


Is there any way to live-update this
$scope
information in the
$stateParams
??

How can I accomplish a live change in both templateUrl as well as URL of the page?

Answer

You should do that by specifying parameters in the url, and templateUrl a function with injected $stateParams:

  .state('form', {
        url: '/:locale/form',
        templateUrl: function($stateParams) { return $stateParams.locale + '/form.html' },
        controller: 'formController'
    })