AngularJs default language AngularTranslation - angularjs

I want to set default language by user country, but i cannot set preferredLanguage in $.get. I am using "http://ipinfo.io". Is there any other way to set default language?
var app = angular.module('test', ['pascalprecht.translate'])
.config(function config($translateProvider, $translatePartialLoaderProvider) {
$translateProvider
.translations('en', {
TRANLATION : 'Translation',
BUTTON_LANG_EN : 'English',
BUTTON_LANG_SK : 'Slovak',
HOME: 'Home',
})
.translations('sk', {
TRANLATION : 'Preklad',
BUTTON_LANG_EN : 'Anglicky',
BUTTON_LANG_SK : 'Slovensky',
HOME: 'Zakladne informacie',
});
$.get("http://ipinfo.io", function(response) {
if(response.country == 'SK'){
$translateProvider.preferredLanguage('sk');
}else{
$translateProvider.preferredLanguage('en');
}
}, "jsonp");
});

You are probably running in an async issue, so, when the ajax call $.get (assuming is jQuery) is resolved you are out from the config phase of angular js...
Try something like that:
in app.js
var app = angular.module('langTest', ['pascalprecht.translate','calsethTranslate'])
.config(function($injector, $translateProvider){
jQuery
.when({})
.then(function() {
return $.get('http://ipinfo.io', function(response) {
return response;
},'jsonp')
})
.then(function(response) {
var lang = response.country === 'SK' ? 'SK' : 'EN';
var _$injector = angular.element(document.body).injector();
console.log(lang);
if (_$injector.has('$translate')) {
console.log("has "+lang);
return _$injector.get('$translate').use(lang);
}
})
});

Related

How to get id from url in Angularjs

In my angularjs project the rooting is like this
{
name: 'room-edit',
config: {
url: '/:view?id',
templateUrl: function (params) {
var view = params.view || 'index';
return '/general/' + view + '.html?v=' + version;
},
isSecure: true,
parent: 'generalMaster',
}
}
In the html page I am calling a function to get the information of the Room obj
<div data-ng-init="getRoom()">
And the getRoom() is like this
$scope.getRoom = function () {
var roomid = 15344;
$http.get("/rest/room/get/" + roomid + "?format=json").then(function
(result) {
$scope.room = result.data;
});
};
How can i get the room id from the query string?
Import $location like $scope in controller and
Try this
$location.search()['id']
or
$location.search()['roomid']

AngularJS: after-select-item not triggering

I am using angularjs version 1.6.4 with angular-multiple-select module for multi selecting. Every thing is working fine. I am able to select from suggestions but whenever i do selection "after-select-item" directive is not triggering. According to angular-multiple-select module documentation
afterSelectItem : Listen for event before adding an item
<div class="form-group float-label-control">
<label>Skills</label>
<multiple-autocomplete ng-model="model.user.skills"
object-property="name"
after-select-item="model.afterSelectItem"
suggestions-arr="model.skills">
</multiple-autocomplete>
</div>
My controller few code lines:
(function () {
"use strict";
var module = angular.module(__appName);
function fetchSkills($http) {
return $http.get(__apiRoot + "/skills")
.then(function (response) {
return response.data;
})
}
function controller($http) {
var model = this;
model.$onInit = function () {
fetchSkills($http).then(function (skills) {
model.skills = skills;
});
};
model.afterSelectItem = function (item) {
console.log("after select item");
console.log(item);
}
}
module.component("userEdit", {
templateUrl: "components/user-edit/user-edit.template.html",
bindings: {
userId: "<",
onUserSaved: "&"
},
controllerAs: "model",
controller: ["$http", controller]
});
}());

How to add a custom query in JHipster?

I am learning to use JHipster and can't figure out how to use create a custom query.
In my project I have Orders table with DeliveryDay and Week fields and want to show only orders for current day of the week. DeliveryDay and Week is int with values (1-7 and 0-2)
So in OrdersRepository.java I added custom query like this:
public interface OrdersRepository extends JpaRepository<Orders,Long> {
Page<Orders> findByDeliveryDayAndWeek(int weekday, int week, pageable);
in OrdersResource.java i added this one:
#RequestMapping(value = "/today",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<List<Orders>> getOrdersForToday(Pageable pageable)
throws URISyntaxException {
log.debug("REST request to get a page of Orderss");
Page<Orders> page = ordersRepository.findByDeliveryDayAndWeek(1, 0, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/today");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
I also added today.html (copied orders.html) and today.js
'use strict';
angular.module('fruitcrmApp')
.config(function ($stateProvider) {
$stateProvider
.state('today', {
parent: 'entity',
url: '/today',
data: {
authorities: ['ROLE_USER'],
pageTitle: 'fruitcrmApp.orders.home.title'
},
views: {
'content#': {
templateUrl: 'scripts/app/custom/today.html',
controller: 'OrdersController'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('orders');
$translatePartialLoader.addPart('global');
return $translate.refresh();
}]
}
})
});
and add today.js in the index.html
My orders.controller.js looks like this (generated by JHipster)
'use strict';
angular.module('fruitcrmApp')
.controller('OrdersController', function ($scope, $state, Orders, OrdersSearch, ParseLinks) {
$scope.orderss = [];
$scope.predicate = 'id';
$scope.reverse = true;
$scope.page = 1;
$scope.loadAll = function() {
Orders.query({page: $scope.page - 1, size: 20, sort: [$scope.predicate + ',' + ($scope.reverse ? 'asc' : 'desc'), 'id']}, function(result, headers) {
$scope.links = ParseLinks.parse(headers('link'));
$scope.totalItems = headers('X-Total-Count');
$scope.orderss = result;
});
};
$scope.loadPage = function(page) {
$scope.page = page;
$scope.loadAll();
};
$scope.loadAll();
$scope.search = function () {
OrdersSearch.query({query: $scope.searchQuery}, function(result) {
$scope.orderss = result;
}, function(response) {
if(response.status === 404) {
$scope.loadAll();
}
});
};
$scope.refresh = function () {
$scope.loadAll();
$scope.clear();
};
$scope.clear = function () {
$scope.orders = {
details: null,
orderDate: null,
firstDelivery: null,
isActive: false,
id: null
};
};
});
Now I can access http://localhost:3000/#/today but it shows all data from Orders what I did wrong? How to use my own method from OrdersRepository.java?
I tried to search for examples but didn't found any relevant. What are the needed steps I missed? Link for some tutorial where it is covered will be great if answer will be to long.
You need to create a new angular service for your today API endpoint. Something like this, called orders-today.service.js:
'use strict';
angular.module('fruitcrmApp')
.factory('OrdersToday', function ($resource) {
return $resource('api/orders/today', {}, {
'query': { method: 'GET', isArray: true}
});
});
Then in your orders.controller.js file, you need to inject your new OrdersToday service:
.controller('OrdersController', function ($scope, $state, Orders, OrdersSearch, OrdersToday, ParseLinks) {
When you want to get the list of today's orders, you need to use OrdersToday.query just like you used Orders.query in the example you pasted.
You will probably want to create a OrdersTodayController with references to OrdersToday, and use that in today.js instead of OrdersController.

Common service for sessionstorage in angularjs

Hi in my application i am setting the values in login controller and getting in all the other js files, other than this how to use a common service for setting storage and getting that storage in required js files
My login controller
app.controller('LoginController',function(loginService, $rootScope,$scope, $http,$location) {
$scope.login = function () {
$scope.log=loginService.getLogin( $scope.emailId , $scope.password).
then(function (response) {
console.log($scope.log);
console.log(response)
if (response.data.LoginVerificationResult.length === 0) {
alert('details are not Available for this emailId');
$scope.error=true;
} else {
$rootScope.name=response.data.LoginVerificationResult[0].UserName;
$scope.abc=response.data.LoginVerificationResult[0].UserType
console.log($scope.abc+"from.......");
sessionStorage.setItem("EmaiId",$scope.emailId);
sessionStorage.setItem("User Id",response.data.LoginVerificationResult[0].UserID);
sessionStorage.setItem("UserName",response.data.LoginVerificationResult[0].UserName);
sessionStorage.setItem("UserType",response.data.LoginVerificationResult[0].UserType);
$scope.UserType = sessionStorage.getItem("UserType");
console.log($scope.UserType +"from login controller")
$location.path('/dashboard')
}
});
};
});
My changepassword file
app.controller("ChangePwdController", function($scope, $http, $location,
BaseUrl, changePwdService) {
//$scope.roleId = sessionStorage.getItem("Role ID");
/* $scope.UserType = sessionStorage.getItem("UserType");*/
$scope.username = sessionStorage.getItem("UserName");
$scope.userType = sessionStorage.getItem("UserType");
$scope.EmpName=sessionStorage.getItem("EmpName");
$scope.patientName=sessionStorage.getItem("PatientName")
$scope.changePwd = function() {
$scope.emailAddress = sessionStorage.getItem("EmaiId");
console.log($scope.emailAddress)
var data = {
'emailAddress' : $scope.emailAddress,
'currentPassword' : $scope.opassword,
'newPassword' : $scope.npassword
};
console.log("Hi")
$scope.pwd=changePwdService.postChangePwd(data).success(
function(resp) {
$scope.PostDataResponse = data;
console.log($scope.pwd)
console.log($scope.PostDataResponse);
if (resp.ResetPasswordResult === true) {
alert("Successfully changed");
console.log("success")
$location.path('/dashboard');
} else {
console.log("fail")
alert("Enter valid current password")
}
})
}
})
Is there any alternative way to set and get in one file
There are ways in which you can achieve the same. Please refer this here.

What is the proper way to allow for "subdirectories" in Backbone Marionette routers?

Here is my current router:
CRM.Router = Marionette.AppRouter.extend({
appRoutes: {
"customers" : "listCustomers",
"customers/:id" : "showCustomer",
"customers/add" : "newCustomer",
"customer/search" : "showCustomerSearch"
}
});
CRM.navigate = function (route, options) {
options || (options = {});
Backbone.history.navigate(route, options);
}
CRM.getCurrentRoute = function () {
return Backbone.history.fragment;
}
CRM.addInitializer(function () {
var router = new CRMApp.Router({
controller: API
});
});
CRM.on("initialize:after", function () {
if (Backbone.history) {
Backbone.history.start({ pushState: true, root: '/app/' });
if (this.getCurrentRoute() === "") {
CRM.trigger("customers:list");
}
}
});
Going to customers works wonderfully, but going to customers/add seems to want to load the customers content. Not sure why. Is there a different way I should be handling customers to allow for subsections?
Suggestions?
Just reordered the routes and it worked:
CRM.Router = Marionette.AppRouter.extend({
appRoutes: {
"customers" : "listCustomers",
"customers/add" : "newCustomer",
"customers/:id" : "showCustomer",
"customer/search" : "showCustomerSearch"
}
});

Resources