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']
Related
I have a problem with the typeahead directive. I try to get datas from my datas from my service via $http.get.
In the console output I can see that my datas are coming from the service but I don't get the popup window of the results.
Here is my code:
Html Template:
<input type="text" class="form-control" placeholder="Kundensuche" ng-model="selectedCompany" typeahead="c for c in companies($viewValue)" typeahead-no-results="noResults" typeahead-min-length="3">
Service:
var _search = function (route, id) {
return $http.get(serviceBase + 'api/' + route + '/search/' + id);
};
serviceHelperFactory.search = _search;
Controller:
$scope.companies = function (val) {
var output = [];
var promise = serviceHelper.search('companies', val);
promise.then(function (result) {
result.data.forEach(function (company) {
output.push(company.companyName);
//output.push(company);
});
console.log(output);
}, function (error) {
adminInvoiceService.serviceErrorMessage(error);
});
return output;
}
Thanks!
Ok, I fixed it!
For all with the same problem here is my solution!
$scope.companies = function (val) {
return $http.get('http://localhost:5569/api/companies/search/'+val).then(function (res) {
var companies = [];
console.log(companies);
res.data.forEach(function (item) {
companies.push(item);
});
console.log(companies);
return companies;
});
};
I am working on a application where i am paginating through some records by making calls to the server like random/api/endpoint?page=1/2/3
Now i while i paginate,
i need to append the page i am requesting to the url like http://www.paginate.com/somedata/{1/2/3} and on opening this url it should also fetch that specific page in the view {meaning if i navigate to hhtp://www.paginate.com/somedata/4 then the app/view should reflect data from the api call random/api/endpoint?page=4}.
Presently i am using angular-route 1.4.12 with the same version of AngularJS. Very new to angular (2 days), any help will be greatly appreciated.
EDIT : What i want to do ?
When i click next while paginating, it should append the pageNumber to the url.
route.js
angular
.module('mainRouter', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/somedata/:page', {
templateUrl: 'partials/somedata.html',
controller: 'PaginationCtrl',
controllerAs: 'vm',
reloadOnSearch: false
}).
otherwise( { redirectTo: "/somedata/1" });
}
]);
PaginationCtrl.js
angular
.module('controllers.Pagination', [])
.controller('PaginationCtrl', PaginationCtrl);
PaginationCtrl.$inject = ['$routeParams', 'paginationService'];
function PaginationCtrl ($routeParams, paginationService) {
var vm = this;
vm.paginationData = {
perPage: 10,
currentPage: 1
};
vm.isLoading = false;
vm.paginate = paginate;
paginate(vm.paginationData.currentPage);
calculateTotalPages();
function calculateTotalPages () {
paginationService.findAll(0, 0)
.success(function (res) {
var paginationData = vm.paginationData || {};
paginationData.totalPages = Math.ceil(res.count / paginationData.perPage);
})
.error(function (res) {
console.log('Error trying to get the total number of pages', res);
});
}
function paginate (pageNumber, perPage) {
vm.isLoading = true;
var paginationData = vm.paginationData || {};
if (! perPage) {
perPage = paginationData.perPage;
}
console.log($routeParams);
paginationService.findAll(perPage, pageNumber)
.success(function (res) {
paginationData.items = res.documents;
vm.isLoading = false;
})
.error(function (res) {
console.log('Error fetching more Logs', res);
});
}
}
PaginationService.js
angular
.module('services.Pagination', [])
.service('paginationService', PaginationService);
PaginationService.$inject = ['$http', 'Constants'];
function PaginationService ($http, Constants) {
// console.log($http);
this.findAll = function (perPage, page) {
var url = Constants.baseUrl + '/sms/get/data';
if (page > 0) {
url += '?page=' + page;
}
return $http.get(url);
};
}
directive being used
var app = angular.module('directives.Pagination', []);
app.directive('pagination', [function () {
return {
restrict: 'E',
template: '<div class="ui pagination menu"> \
<a class="icon item" ng-click="vm.previous()"><i class="left arrow icon"></i></a> \
<div class="icon item">{{ vm.paginationData.currentPage }} / {{ vm.paginationData.totalPages }}</div> \
<a class="icon item" ng-click="vm.next()"><i class="right arrow icon"></i></a> \
</div>',
scope: '=',
link: function (scope, element, attrs) {
var vm = scope.vm;
vm.paginationData.currentPage = 1;
vm.next = function () {
vm.paginationData.currentPage++;
if (vm.paginationData.currentPage > vm.paginationData.totalPages) {
vm.paginationData.currentPage = vm.paginationData.totalPages;
}
vm.paginate(vm.paginationData.currentPage);
};
vm.previous = function () {
vm.paginationData.currentPage--;
if (vm.paginationData.currentPage < 1) {
vm.paginationData.currentPage = 1;
}
vm.paginate(vm.paginationData.currentPage);
};
}
};
}]);
You should be able to access your :page parameter via $routeParams, which you've already injected in your controller.
Just call paginate with $routeParams.page instead of your default of 1.
In order to update the url as you go (in such a way that allows the user to copy the url for later use), without updating the route and re-initializing the controller, you can just call $location.search({page: page}). When this is called with reloadOnSearch set to false (as you've already done) it shouldn't re-initalize the controller.
Lastly, in case its not clear, you'll have to update the URL at the same time you make your API call. There isn't a built in angular way to do this, but it should be pretty straightforward.
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.
I'm trying to unit test a controller which relies on resolve keys using Jasmine. I am also using the controllerAs syntax. The routing code is as follows:
$routeProvider.when('/questions', {
templateUrl: 'questions/partial/main_question_viewer/main_question_viewer.html',
controller:'MainQuestionViewerCtrl',
controllerAs:'questionCtrl',
resolve: {
default_page_size: ['QuestionService', function (QuestionService) {
//TODO Work out page size for users screen
return 50;
}],
starting_questions: ['QuestionService', function (QuestionService) {
var questions = [];
QuestionService.getQuestions(1).then(
function(response){
questions = response;
}
);
return questions;
}],
},
});
The controller (so far):
angular.module('questions').controller('MainQuestionViewerCtrl',
[
'QuestionService',
'starting_questions',
'default_page_size',
function (QuestionService, starting_questions, default_page_size) {
var self = this;
//Model Definition/Instantiation
self.questions = starting_questions;
self.page_size = default_page_size;
self.filters = [];
//Pagination Getters (state stored by QuestionService)
self.current_page = function(){
return QuestionService.get_pagination_info().current_page_number;
}
self.page_size = function(page_size){
if(page_size != null){
QuestionService.set_page_size(page_size);
}
return QuestionService.get_page_size();
}
}
]
);
And the test code:
describe('MainQuestionViewerCtrl', function () {
//===============================TEST DATA=====================================
var allQuestionsResponsePage1 = {
count: 4,
next: "https://dentest.com/questions/?format=json&page=2&page_size=1",
previous: null,
results: [
{
id: 1,
subtopic: {
topic: "Math",
name: "Algebra"
},
question: "if a=3 and b=4 what is a+b?",
answer: "7",
restricted: false
}
]
};
beforeEach(module('questions'));
beforeEach(module('globalConstants')); //Need REST URL for mocking responses
var ctrl, qService;
var backend,baseURL;
//inject dependencies
beforeEach(inject(function ($controller, $httpBackend,REST_BASE_URL) {
ctrl = $controller('MainQuestionViewerCtrl');
backend = $httpBackend;
baseURL = REST_BASE_URL;
}));
//inject QuestionService and set up spies
beforeEach(inject(function (QuestionService) {
qService = QuestionService;
}));
//Convenience for adding query params to mocked requests
var buildParams = function (page, page_size) {
var params = {
format: 'json',
page: page,
page_size: page_size,
};
var keys = Object.keys(params).sort(); //how angular orders query params
var returnString = '?' + keys[0] + '=' + params[keys[0]] +
'&' + keys[1] + '=' + params[keys[1]] + '&' + keys[2] + '=' + params[keys[2]];
return returnString;
};
describe('Instantiation',inject(function ($controller) {
beforeEach(module($provide){
beforeEach(inject(function ($controller) {
//Make a mock call to the server to set up state for the QuestionService
backend.expectGET(baseURL + '/questions/' + buildParams(1, 1)).respond(200, allQuestionsResponsePage1);
qService.getQuestions(1);
backend.flush();
//Now mock the result of resolve on route
ctrl = $controller('MainQuestionViewerCtrl', {
default_page_size: 1,
starting_questions: allQuestionsResponsePage1,
});
}));
it('should start with the first page of all the questions pulled down', function () {
expect(qService.questions).toEqual(allQuestionsResponsePage1);
});
it('should start on page 1', function () {
expect(qService.current_page).toEqual(1);
});
it('should start with the page size set to the default passed in',function(){
expect(qService.page_size).toEqual(1);
})
}));
When trying to run the tests, Angular is complaining that it cant resolve starting_questions or default_page_size because the providers for them aren't known.
It worth pointing out that the reason for mocking the HTTP request for the QuestionService is that it builds pagination info based on the response, which the controller will then access to determine the paginator size/numbers in the UI.
Solved. I was instantiating the controller in the outer describe without passing in mock values for the resolve key dependecies. That was causing the error: the method of instantiating the controller with the mock dependecies works fine.
I am using the Select2 as a typeahead control. The code below works very well when the user types in the search term.
However, when loading data into the page, I need to be able to manually set the value of the search box.
Ideally something like: $scope.selectedProducerId = {id:1, text:"Existing producer}
However, since no data has been retrieved the Select2 data source is empty.
So what I really need to be able to do is to add a new array of data to the datasource and then set the $scope.selectedProducerId, something like: $scope.producersLookupsSelectOptions.addNewData({id:1, text:"Existing producer}) and then
$scope.selectedProducerId = 1;
Researching this I have seen various suggestions to use initSelection(), but I can't see how to get this to work.
I have also tried to set createSearchChoice(term), but the term is not appearing in the input box.
I would be most grateful for any assistance.
Thanks
This is the html
<div class="col-sm-4">
<input type="text" ui-select2="producersLookupsSelectOptions" ng- model="selectedProducerId" class="form-control" placeholder="[Produtor]" ng-change="selectedProducerIdChanged()"/>
</div>
This is the controller
angular.module("home").controller("TestLookupsCtrl", [
"$scope", "$routeParams", "AddressBookService",
function($scope, $routeParams, AddressBookService) {
$scope.producersLookupsSelectOptions = AddressBookService.producersLookupsSelectOptions();
}
]);
This is the service:
angular.module("addressBook").service("AddressBookService", [
"$http", "$q", function($http, $q) {
var routePrefix = "/api/apiAddressBook/";
//var fetchProducers = function(queryParams) {
// return $http.get(routePrefix + "GetClientsLookup/" + queryParams.data.query).then(queryParams.success);
//};
var _getSelectLookupOptions = function(url, minimumInputLength, idField, textField) {
var _dataSource = [];
var _queryParams;
return {
allowClear: true,
minimumInputLength: minimumInputLength || 3,
ajax: {
data: function(term, page) {
return {
query: term
};
},
quietMillis: 500,
transport: function(queryParams) {
_queryParams = queryParams;
return $http.get(url + queryParams.data.query).success(queryParams.success);
},
results: function(data, page) {
var firstItem = data[0];
if (firstItem) {
if (!firstItem[idField]) {
throw "[id] " + idField + " does not exist in datasource";
}
if (!firstItem[textField]) {
throw "[text] " + textField + " field does not exist in datasource";
}
}
var arr = [];
_.each(data, function(returnedData) {
arr.push({
id: returnedData[idField],
text: returnedData[textField],
data: returnedData
});
});
_dataSource = arr;
return { results: arr };
}
},
dataSource: function() {
return _dataSource;
},
getText: function (id) {
if (_dataSource.length === 0) {
throw ("AddressBookService.getText(): Since the control was not automatically loaded the dataSource has no content");
}
return _.find(_dataSource, { id: id }).text;
}
//initSelection: function(element, callback) {
// callback($(element).data('$ngModelController').$modelValue);
//},
//createSearchChoice:function(term) {
// return term;
//},
addNewData:function(data) {
this.ajax.results(data,1);
};
};
return {
producersLookupsSelectOptions: function() {
var url = routePrefix + "GetClientsLookup/";
return _getSelectLookupOptions(url, 2, "Id", "Name");
},
}
}
]);