Angular dynamcly setting the user's language - javascript

I have a service that fetches the Userinfo which contains his or hers preferred language and I want to use it in my controller to change the language of my application when the user loggs in,
however when I do '$scope.User.locale' which should return the preferred language I keep getting undefined.
My code is:
(function () {
'use strict';
var controllers = angular.module('portal.controllers');
controllers.controller('mainController', function mainController($scope ,UserService, NavigationService, $translate, localStorageService) {
localStorageService.clearAll();
$scope.User = UserService.getUserinfo();
$scope.setLang = function (langKey) {
$translate.uses(langKey);
$.removeCookie(Constants.cookie_locale);
var domain = document.domain;
$.cookie(Constants.cookie_locale, langKey, {path: "/", domain: domain});
};
$scope.logout = function(){
NavigationService.logout();
};
console.log($scope.User);
console.log($scope.User.locale);
$translate.uses($scope.User.locale);
});
}());
UserService:
(function(){
'use strict';
var userServices = angular.module('portal.services');
userServices.factory('UserService', ['UserInfo','localStorageService', function(UserInfo, localStorageService){
return new UserService(UserInfo, localStorageService);
}]);
function UserService(UserInfo, localStorageService){
this.UserInfo = UserInfo;
this.localStorageService = localStorageService;
}
UserService.prototype.getUserinfo = function(){
var userinfo = this.localStorageService.get(Constants.key_userinfo);
if(userinfo !== null){
return userinfo;
} else {
return this.UserInfo.query($.proxy(function(data){
this.localStorageService.add(Constants.key_userinfo, JSON.stringify(data));
}, this));
}
};
UserService.prototype.clearUserInfo = function(){
this.localStorageService.remove(Constants.key_userinfo);
};
}());
Userinfo:
(function(){
'use strict';
var data = angular.module('portal.data');
data.factory('UserInfo', function($resource){
return $resource('/users-rs/api/userinfo',{}, {
query: {method: 'GET'}, isArray: false}
);
});
}());
$scope.User does bind the correct features to the elements I want so I know it's somewhere in there :p, Also when the page is loaded and the setLang function is called it does it's magic, now I only need to get it working on initial loading of the app.
Thx for checking into it
J.

Related

How to pass form data to another page?

im using angularJS v 1.5.6 and want to know how to pass my form data correctly with $location.path.
Here is my code Page A:
<form>
...
<button type="submit" ng-click="submit(formData)">submit</button>
</form>
JS:
app.config(['$routeProvider', function ($routeProvider) {$routeProvider
// Home
.when("/", {
templateUrl: "A.html",
controller: "ACtrl"
})
.when("/B/", {
templateUrl: "B.html",
controller: "BCtrl"
})
//fallback url if nothing matches
.otherwise({
redirectTo: '/'
});
}]);
app.controller('ACtrl', function ( $scope, $location, $http) {
$scope.formData = {};
$scope.submit = function() {
$location.path("/B/" + $scope.formData );
};
});
//controller for B page
app.controller('BCtrl', ['$scope', '$routeParams',
function($scope,$routeParams) {
$scope.formData = $routeParams.formData;
}]);
it is a pretty simple example, but i cant figure out how to solve it :(
By clicking the submit nothing happens. If i remove the $scope from $scope.formData i get a error like: Error: formData is not defined.
The terms in formdata are available, i tested it with console.log($scope.formData) and everything is ok.
here is the link plunker: https://plnkr.co/edit/K5zwcmRRyom5HR4a5Q9o
EDIT
the only issue is now, how to handle the select object correctly in the foreach loop. Need help please
You can do it by creating a service and using setter/getter in order to transfer a variable.
For example like this: https://plnkr.co/edit/IuTXsVLU7dq3TylfnSYP?p=preview
app.service('TransferService', [function(){
var savedData,
service = {
getData: getData,
setData: setData
}
function getData(){
return savedData
}
function setData(data){
savedData = data
}
return service
}])
Don't use location.path...
You could either use a service or use localstorage (or some other browser storage mechanism [sessionStorage, indexdb].
Service Method Below
app.service("SomeService", function () {
var value = null;
this.set = function (val) {
value = val;
return this;
}
this.get = function () {
return value;
}
})
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
SomeService.set($scope.formData);
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
//Check that the data is present in the SomeService service.
var dataFromACtrl = SomeService.get();
if (dataFromACtrl) {
$scope.formData = dataFromACtrl;
}
})();
})
Using localStrorage below, could be sessionStorage.
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
window.localStorage.setItem("form_data", JSON.stringify($scope.form_data));
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
var dataFromACtrl = window.localStorage.getItem("form_data");
if (dataFromACtrl) {
$scope.formData = JSON.parse(dataFromACtrl);
}
})();
})
Note
Using the localStorage example you would need to do some clean-up, after doing whatever you want to do with that data in Bctrl you'd want to clear the entry in localstorage using either of the below lines of code:
window.localStorage.removeItem("form_data");
delete window.localStorage["form_data"];

AngularJS: Code worked in Controller but not in factory: Possibly unhandled rejection: {}

After building the Web API, I just promoted a controller to a service (.factory) to share that data with other controllers in AngularJS.
However it seems that I have a syntax error and the factory is not accepted as it.
This is my App.js:
//appContacts.js
(function () {
"use strict";
var app = angular.module("appContacts", ["simpleControls", 'ui.router', 'ngResource'])
.config(a lot of stuff here)
.factory('ContactService', function ($resource) {
var ContactService = {};
var vm = this;
vm.contacts = [];
vm.newContact = {};
vm.errorMessage = "";
vm.isBusy = true;
// Load all contacts
ContactService.getContacts = function () {
return $resource.get("api/contacts")
.then(function (response) {
angular.copy(response.data, vm.contacts);
}
);
};
//Set Current Contact
ContactService.setCurrentContact = function (contact) {
vm.currentContact = contact;
return vm.currentContact;
};
return ContactService;
})
})();
and this is my contatcsController:
//contactsController.js
(function () {
"use strict";
angular.module("appContacts")
.controller("contactsController", function (ContactService) {
//Get all Contacts
ContactService.getContacts = function () {
vm.contacts = contacts;
}
vm.setCurrentContact = function (contact) {
vm.currentContact = contact;
};
})
})();
I keep getting this error: Possibly unhandled rejection: {} in the Console and nothing shows in the front end.
Does anybody has an idea why it does not work as factory the same code that worked inside the controller?
More details at https://github.com/angular-ui/ui-router/issues/2889
app.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);

AngularJS: Controller variable not updating despite being bound to service variable

Problem: A controller variable vm.boatList (intended to be bound to a service variable, SearchService.boatList) is not updating with the service variable.
Code Snippets: Complete code at the bottom.
Controller
function SearchController($stateParams, SearchService) {
var vm = this;
vm.boatList = SearchService.boatList;
Service
function SearchService(BoatsDataService) {
var service = {
boatList: null,
getBoatList: getBoatList,
params: {}
};
return service;
Additional Data:
The getBoatList function called from the controller works - it logs data from the SearchService to the console. When I log vm.boatList immediately afterward, it's null.
Also, <div ng-repeat="boat in SearchController.boatList">...</div> only works when I assign directly to vm.boatList.
Console Output:
Array[3]
null
Complete Controller:
(function () {
'use strict';
angular.
module('trips').
controller('SearchController', SearchController);
SearchController.$inject = ['$stateParams', 'SearchService'];
function SearchController($stateParams, SearchService) {
var vm = this;
vm.boatList = SearchService.boatList;
vm.initialParams = getParams();
activate();
////////////////////
function activate() {
setInitialParams();
SearchService.getBoatList()
.then(function (data) {
SearchService.boatList = data;
console.log(SearchService.boatList); // Logs data.
console.log(vm.boatList); // Logs null.
})
.catch(function (error) {
console.log(error);
});
}
function getParams() {
var params = {
location: $stateParams.location,
passengers: $stateParams.passengers,
maxPrice: $stateParams.maxPrice,
minPrice: $stateParams.minPrice,
embark: $stateParams.embark,
disembark: $stateParams.disembark,
category: $stateParams.category
};
return params;
}
function setInitialParams() {
SearchService.params = getParams();
}
}
})();
Complete Service:
(function () {
'use strict';
angular.
module('trips').
factory('SearchService', SearchService);
SearchService.$inject = ['BoatsDataService'];
function SearchService(BoatsDataService) {
var service = {
boatList: null,
getBoatList: getBoatList,
params: {}
};
//$scope.$watch('service.params', function () {
// getBoatList().then(function (data {
// service.boatList = data;
// })
// }, true
//);
return service;
//////////////////////
function getBoatList() {
return BoatsDataService.BoatList
.query(service.params)
.$promise
}
}
})();
Recap: I don't know how to two-way bind, I guess.
When you're trying to bind a variable that's directly on the service, it will fail (see call by sharing). However, if you wrap it with an object, it will work like you expect, see this Fiddle.
So in your case, if you bind an object inside the service to your controller, it should be fine -
Service:
var service = {
boatListObj : {
boatList: null
},
getBoatList: getBoatList,
params: {}
};
Controller:
vm.boatListObj = SearchService.boatListObj;
Promise response:
.then(function (data) {
SearchService.boatListObj.boatList = data;
console.log(SearchService.boatListObj.boatList); // Logs data.
console.log(vm.boatListObj.boatList); // Should log fine now
})
The reason why <div ng-repeat="boat in SearchController.boatList">...</div> is not working is because SearchController.boatList is not on the $scope. It either must be on the $scope, or addressed via ControllerAs syntax when it's placed on the controller.

Parse/AngularJS - Input data with user id

I'm working on a Parse App with AngularJS, and reworking a controller to point to the logged in user when posting. On my database table, I've set a column "author" to point to the users. I made a separate service.js file which I call with Squeeg. When I click create, it does not input the data with the user.id. It works fine without it. How would I fix this to ensure that the user objectId is a part of the data is added to the database?
$scope.create=function(){
var user = Parse.User.current();
console.log(user.id);
Squeeg.create({ author:user.id, eventname:$scope.events.title, eventDescription:$scope.events.description}).success(function(data){
alert("done");
});
}
Since I need 50 reputation to comment, this needs to be asked here, have you accessed authfactory/authserverice to get the current user from there? Assuming you have login?
Then in authFactory you could have something like this.
app.factory('authFactory', ['$http', '$window', function ($http, $window) {
var authFactory = {};
authFactory.logIn = function (user) {
return $http.post('/login', user).success(function (data) {
authFactory.saveToken(data.token);
});
};
authFactory.saveToken = function (token) {
$window.localStorage['appToken'] = token;
};
authFactory.getToken = function () {
return $window.localStorage['appToken'];
};
authFactory.logOut = function () {
$window.localStorage.removeItem('appToken');
};
authFactory.currentUser = function () {
if(authFactory.isLoggedIn()){
var token = authFactory.getToken();
var payload = JSON.parse($window.atob(token.split('.')[1]));
return payload.username; // or return payload.id ..... / return payload
}
};
authFactory.isLoggedIn = function () {
var token = authFactory.getToken();
if(token){
var payload = JSON.parse($window.atob( token.split('.')[1]) );
return payload.exp > Date.now() / 1000;
} else {
return false;
}
};
return authFactory;
}]);
Then all you need to do is binding it with your controller to access it.
app.controller('AnyCtrl', ['$scope', 'authFactory',
function ($scope, authFactory) {
$scope.currentUser = authFactory.currentUser;
}
]);

TypeError: Cannot read property 'getAccounts' of undefined

I'm following John Papa's Angular Style guide for creating a small application, and I can't seem to work out an issue with the controller using a method from a service...
module
(function () {
'use strict';
var accountsApp = angular.module('accountsApp', ['ui.bootstrap', 'ngAnimate']);
})();
Controller
(function() {
'use strict';
angular
.module('accountsApp')
.controller('accountsCtrl', accountsCtrl);
accountsCtrl.$inject = ['$log'];
function accountsCtrl($log, accountsDataSvc) {
/* jshint validthis:true */
var vm = this;
vm.title = 'Accounts';
vm.accounts = [];
vm.accountForm = null;
vm.account = { id: 0, name: '', description: '' }
activate();
function activate() {
return getAccounts(1).then(function() {
$log.info('Accounts loaded');
});
}
function getAccounts(id) {
return accountsDataSvc.getAccounts(id).then(function(data) { //error here
vm.accounts = data;
return vm.accounts;
});
}
}
})();
Service
(function () {
'use strict';
angular
.module('accountsApp')
.factory('accountsDataSvc', accountsDataSvc);
accountsDataSvc.$inject = ['$http', '$log'];
function accountsDataSvc($http, $log, $q) {
var uri = '***';
var service = {
getAccounts: accounts
};
return service;
//////////////////////
function accounts(userId) {
$log.info(uri + userId + ' called');
return $http.get(uri + userId)
.then(getAccountsComplete)
.catch(function (message) {
$log.error('XHR Failed for getAccounts ' + message);
});
function getAccountsComplete(data, status, headers, config) {
return data.data[0].data.results;
}
}
}
})();
When I run the application, I get the error TypeError: Cannot read property 'getAccounts' of undefined within the controller, but I can't see where I have gone wrong - any assistance would be much appreciated.
It looks like you forgot to inject accountsDataSvc into your controller
Try:
accountsCtrl.$inject = ['$log', 'accountsDataSvc'];

Categories

Resources