I'm just begining with angularJS and I want add the option of translation to my application.
I tried this fonction with one variable for my first test with 2 button which refer to 2 differents languages, the local language is ENGLISH and the second is FRENSH and it work but the probleme is after refreshing my application, this variable turn to the local language. how can I resolve this problem . this is my code on angularJS.
'use strict';
var app = angular.module('app', ['pascalprecht.translate']);
app.config(function($translateProvider) {
$translateProvider.fallbackLanguage('en');
$translateProvider .translations('en', {
msg : 'Hello',
})
$translateProvider.translations('fr', {
msg : 'bonjour'
});
$translateProvider.preferredLanguage('en');
});
app.controller('Ctrl', function($translate, $scope) {
$scope.changeLanguage = function (langKey) {
$translate.use(langKey);
};
});
Thank you
You will probably want to use some kind of a localStorage service to save the selected language.
You'll have to decide which kind of persistence (by session? by user?) you want to attain, to choose the best model of persistence to use...
You should use a way to persist data during life time of your aplication.
for example you can use cookies.
But if you want to do it angular way you can use $localStorage or $sessionStorage from this repo
there are other repositories as well.
After that when user refresh the page you can check
for language information saved in your session($sessionStorage) or browser($localStorage) and display the right language.
as #MarcoS said, if you want to show another
language for specific users you should store and get language information
from database.
goodluck !
Related
I am new to angular js.Please suggest which one is better . I have a page where I can select a no of check boxes and navigate to 2 nd page.I want to show the checked values when I press back button in browser.
Which one is better using $rootScope or stateparam or localstorage.Please consider performance also.
Going through your options one by one:
$rootScope: You should try to avoid using this option as it is associated to the global state. Use this option only if you want the data you set to be globally available throughout the app and do not want to reuse the same variable names anywhere else.
$stateParams: These typically go into the state URI as a dynamic part of the whole URL. This has only limited usage, and may not be a good idea for your use case where you need to store data from multiple checkboxes.
localStorage: This is slower than using a JavaScript variable, and hence not a good idea.
Services:
Here is a better solution for you, entirely within the AngularJS paradigm: AngularJS services
Excerpt from the link in point 3:
Data should also be stored in services, except where it is being bound
to the $scope. Services are singletons that persist throughout the
lifetime of the application, while controllers are transient between
application states. If data is stored in the controller then it will
need to be fetched from somewhere when it is reinstantiated. Even if
the data is stored in localStorage, it's an order of magnitude slower
to retrieve than from with a Javascript variable.
You can use the service to set and get your data inside your controller anywhere in the app in a consistent manner.
Here is an indicative example:
app.factory('formDetails', formDetails);
function formDetails() {
var formData = {};
return {
getProperty: function () {
return formData;
},
setProperty: function(values) {
formData = values;
}
};
};
Use it in your controller as:
app.controller('MyController', [ '$scope', 'formDetails' , function($scope, formDetails) {
$scope.checkboxData = {};
// on load call service 'get' function
$scope.checkboxData = formDetails.getProperty();
// on some event/watch function call service 'set' function
formDetails.setProperty($scope.checkboxData);
}]);
I'm currently make a html page by using angularjs.
I have 1 html page, with 1 sidebar, 1 navigation bar and 1 content area.
Like this : AdminLTE
I've follow this instruction : this
And successfully, my app works ok.
But I don't know how to apply multilingual function to my every app.
For example : Navigationbar is 1 app, sidebar is 1 app and main content is 1 app.
How can I apply 1 translationService to 'em without downloading json again and again ?
Can anyone help me please ? Thank you.
I still think it would be better to have one application for the whole page, but have separate controllers for the nav, sidebar, and main content. That way they all work separately, but you don't have the awkwardness of dealing with separate apps. The only reason I can think of to have separate apps is if you want to make sure that services are NEVER shared between the different parts. However, in your case, it looks like you WANT to share the translate service, so I think it makes sense to use one app.
If you really want to have multiple apps, it is still possible. You can load the translations asynchronously, then when this is done, you call angular.module() for each app and inject the translations as a constant. Then, when you configure the translate provider, you can inject your translation constant just like you would inject any service.
I have done this in an application before, but I don't have access to the code right now. I did it for a single application, but you can easily extend it to multiple applications. I believe it looked similar to this:
var $http = angular.injector().get('$http');
var $q = angular.injector().get('$q');
var promises = [
$http.get('path/to/translations/en.json'),
$http.get('path/to/translations/fr.json'),
];
$q.all(promises)
.then(function(translations) {
angular.module('app', [])
.constant('translations_en', translations[0])
.constant('translations_fr', translations[1])
.config(['$translateProvider', 'translations_en', 'translations_fr',
function($translateProvider, translations_en, translations_fr) {
$translateProvider.translations('en', translations_en);
$translateProvider.translations('fr', translations_fr);
}]);
angular.bootstrap(element, ['app']);
});
For multiple apps, you would need to run the angular.module block once for each app.
Alternatively, you could define separate modules for each part, then define a parent module that depends on the other mini-modules, i.e.
angular.module('navigation', []);
angular.module('sidebar', []);
angular.module('mainPage', []);
angular.module('app', ['navigation', 'sidebar', 'mainPage']);
angular.bootstrap(element, ['app']);
I believe that all modules would share the same translate service in this case.
I am caught up in a situation here.
I have a switch in my login page and i want to redirect my service for authorization accordingly.
I want to load my services dynamically after checking some conditions, when i launch my application for the first time. But in angular as we have ng-app and we need to inject all the modules in it at the start. My base url is set before the app is launched. Is it possible to change my base url on condition?
On launching the application the base url gets assigned before the launch of first page which is login page. I have a switch in my login page which if true, i need to set the different base url. But since the base url is set and the control doesnt come again to this module, i am not able to change it conditionally.
This is in my service.js
angular.module('sampleService', ['ngResource'])
.factory('sample', function ($resource, $rootScope) {
$rootScope.serviceUrl = "http://......";
...
});
This is in my app.js
var app = angular.module("sampleApp", ["sampleService"]);
This is how I am using $routeProvider
app.config(["$routeProvider", function ($routeProvider, $locationProvider) {
...
}]);
I want to change my service url conditionally as:
if(myflag)
$rootScope.serviceUrl = "url1";
else
$rootScope.serviceUrl = "url2";
I hope this will give some idea of what i want to do and what i am doing.
Thanks in advance.
I suppose you're using ngRoute in your application, right?
Maybe you should look into uiRouter where you control state. And what you're describing could fall into this category.
https://github.com/angular-ui/ui-router
Also read the differences between the two in this Stackoverflow content.
Yes uiRouter is best solution when it comes to dynamic page loading
Here is a simple PDF on how to use ui-sref in your code ,
Simple Example
I'm building an app in which I've got a registration flow divided in 3 parts, Personal Info, Profile picture, and so on, each one in its invidual view.
So, which way do you think is the best way to persist data between views so in the final step I can show the whole data to the user and ask for confirmation.
Local Storage? $cacheFactory? I've really have no idea how to do it, any advice will be usefull!
Thanks in advance
cookie or local storage is available,but I think Angular way is recommended.
$rootScope: you can storage user data in $rootScope simply use
$rootScope.userData = {
'userName' : 'first',
'userId' : 'second'
};
to storage and read data in new view, remember to inject $rootScope into your controller
$broadcast: angular provide event $broadcast and $emit, so you can use $on to watch event and get your user data.and this is a demo http://jsfiddle.net/whitewolf/5JBA7/15/
route resolve? : if you send user data in every step to database,
you can use resolve in route config to load user data by $http.get().
add a service
app.factory("messageService", function($q){
return {
getMessage: function(){
return $q.when("Hello World!");
}};
});
in route config
$routeProvider
.when("/news", {
templateUrl: "newsView.html",
controller: "newsController",
resolve: {
message: function(messageService){
return messageService.getMessage();
}}
})
in your controller
app.controller("newsController", function (message) {
$scope.message = message;
});
You are looking for an angular wizard
if you are using ui-router, you can easily do this with nested states
have a look
http://scotch.io/tutorials/javascript/angularjs-multi-step-form-using-ui-router
one form ( main state )
separate templates (nested states)
Note: specify controller for main state only and not for nested states
It will depend on the requirement.
If there is a requirement that the user can complete two steps and
come back later to complete the third step, then better go with local
persistence.
But if it's really not the case, you need not use any persistence
mechanism. Only thing is you need to properly map the models. And on the final submit, you can persist the complete input data.
I am looking for advice with regards to creating a generic controller which I can reuse in my application. As an example I have created the following GIST:
https://gist.github.com/heide-de/10832576
but here is the relevant code snippet:
angular.module('genericTestApp', [])
.factory('Names', function() {
return {
names: []
};
})
.controller('IndexController', function(Names) {
Names.names = [
{firstname:'Sarah', surname:'Schmitt'},
{firstname:'Paul', surname:'Wells'},
{firstname:'Felix', surname:'the cat'}
]
})
.controller('SecondIndexController', function(Names) {
Names.names = [
{firstname:'Octo', surname:'Cat'},
{firstname:'Beth', surname:'Appleby'},
{firstname:'Fred', surname:'Bloggs'}
]
})
.controller('TableController', function($scope, Names) {
$scope.names = Names.names;
})
What feels very wrong to me is that the TableController in this example relies on the fact that the injected Names factory needs to have been configured previously in the IndexController.
The next developer that comes along will just inject Names, and will have no idea that it needs configuring prior to that.
Is there a better way of doing this with Angular?
You're right in your approach – Configuring a factory in a controller is always a bad idea. A controller is supposed to contain view specific logic, and in my opinion should even only be included when that particular view is rendered. (that's how I write my apps anyway)
To configure anything when the application loads up, you need run, that should contain all the initial stuff that your app needs to do in the beginning.
This might be a good read.