How to append query string to url in AngularJS? - javascript

I am new to angular js. I have search page with input text box to search for customerId but I want to add a functionality where I can search based on url string as well.
For example, My url is :
http://localhost:8080/#/search
But I need something like
http://localhost:8080/#/search?ACC34ff
http://localhost:8080/#/search?CustomerId so that I can search based on customerId in url also
Can some one tell how can I add query string ?
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'partials/home.html',
controller: 'homePageCtrl',
reloadOnSearch: true
}).when('/features', {
templateUrl: 'partials/features.html',
controller: 'featuresCtrl',
reloadOnSearch: false
}).when('/search', {
templateUrl: 'partials/search.html',
controller: 'searchCtrl',
reloadOnSearch: false
}).otherwise({
redirectTo: '/home'
});
}]);
Controller :
appControllers.controller('searchCtrl', ['$scope','$route','$filter', '$http', '$location','$window','$timeout',
function($scope, $route, $filter, $http, $location, $window, $timeout) {
$scope.searchCustomerFeatures = function () {
if($scope.customerId != null) {
$http.get('/getCustomerFeatures.do', {params: {'customerId': $scope.customerId}}).success(function (data) {
$scope.featuresJson = angular.toJson(data, true);
});
}
}
}]);
Html :
<li ng-class="{active: isActive('/search')}" style="margin-left: 100px; text-decoration-color: black; font-size: 20px">
Search
</li >
Search page :
Thanks

Firstly, I can't believe you haven't got more answers because there are many ways to pass and retrieve a variable over the url, each being slight variations of 2 main ways.
As part of a Query String (as per your request)
As a Route Parameter (also worth mentioning)
The subsequent examples assume that you have a text input for customer id as follows:
<input type="text" ng-model="customerId" />
1) How to pass customerId as part of a Query String
Append ?cId={{ customerId }} to your link as follows:
Search
Now when you click on the link you will be taken to a url such as:
http://localhost:8080/#/search?cId=ACC34ff
You can then pick the cId parameter up in the controller by using the $location service.
app.controller('searchCtrl', function($scope, $location){
var qsCustomerId = $location.search().cId;
// Do what you want with qsCustomerId here...
});
2) How to pass customerId as a Route Parameter
Create a new route that specifies a new cId route parameter:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/search/:cId', {
templateUrl: 'partials/search.html',
controller: 'searchCtrl',
reloadOnSearch: false
})
}]);
Append /{{ customerId }} to your link as follows:
Search
Now when you click on the link you will be taken to a url such as:
http://localhost:8080/#/search/ACC34ff
You can pick the cId parameter up in the controller using the $routeParams service.
app.controller('searchCtrl', function($scope, $routeParmas){
var rpCustomerId = $routeParmas.cId;
// Do what you want with rpCustomerId here...
});

All you need is to pass the customerId as a parameter.
.when('/Search', {
templateUrl: function (params) { return 'partials/search?customer=' + params.CustomerId; }
})
In the follow link there is also an explanation on how to pass multiple parameters, in case you need:
https://stackoverflow.com/a/35967896/5988277

Related

Information doesn't refresh after clicking on link in AngularJS. I've got {{ value }} but not the data

I have an Angular app that takes information from few JSON files.
The first JSON file contains data about cities and managers. Like this:
[
{
"link" : "veliky_novgorod",
"city" : "Великий Новгород",
"manager" : "mr. Sminth",
},
{
"link" : "magnitogorsk",
"city" : "Магнитогорск",
"manager" : "mr. Young",
},...
I use it in order to create a page for every city.
My urls look like this: ...index.html#/cities/veliky_novgorod/, ...index.html#/cities/biisk/, ...index.html#/cities/biisk/mobile/, etc.
Everything works fine, but when I try to go from one page to another information from the other JSON (scopes) doesn't load. After changing page I've always got {{ value }}
But when I make refresh manually, everything is going back to normal.
In other words, how can I reload new page after clicking on link. I tried to use window.location.reload() But it doesn't work.
<li ng-repeat="city in cities">
{{city.manager}}
</li>
My module and controller below:
var curryApp = angular.module('CurryApp', [
'ngRoute',
'curryControllers'
]);
curryApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'link_list.html',
controller: 'CurryListCtrl'
}).
when('/cities/:cityId/', {
templateUrl: 'template-total.html',
controller: 'CurryDetailCtrl'
}).
when('/cities/:cityId/mobile/', {
templateUrl: 'template-mobile.html',
controller: 'CurryMobileCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
That's my controller:
var curryControllers = angular.module('curryControllers', []);
curryControllers.controller('CurryListCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('cities.json').success(function(data) {
$scope.cities = data;
});
}]);
curryControllers.controller('CurryDetailCtrl', ['$scope', '$routeParams', '$http', '$route',
function($scope, $routeParams, $http, $route) {
$scope.reloadRoute = function(){window.location.reload();}
$scope.cityId = $routeParams.cityId;
$http.get('cities.json').success(function(data) {
$scope.cities = data;
$http.get('paidbc.json').success(function(data2) {
$scope.paidBc = data2;
$scope.isActive = function(item) {
return item.link === $scope.cityId;
};
});
});
}]);
curryControllers.controller('CurryMobileCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.cityId = $routeParams.cityId;
}]);
It seems that is an error related with the href attribute. According to docs:
The wrong way to write it:
link1
The correct way to write it:
<a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
In your case, use:
<a ng-href="#/cities/{{city.link}}" ng-click="reloadRoute()">{{city.manager}}</a>
instead of using only href.

AngularJS strange query behavior with UI Router

Have a small search app using Elasticsearch and AngularJS. I'm using $state.go() in my search() on my ng-submit button. searchTerms is my ng-model on the input.
I have 2 controllers, homeCtrl and searchCtrl. homeCtrl is for homepage which is just a search box and provides autocomplete functionality. searchCtrl is for results page and has same search box and provides for results area.
When I have $state.go() like this:
$state.go('search', {q: searchTerms});
It solved a problem I was having, which was
http://localhost:8000/app/search?q=searchTerms
INSTEAD of
http://localhost:8000/app/search?q=userTypedInput
So now the url functions correctly, but the search results do not display...?
When I have
$state.go('search', {q: 'searchTerms'});
The search results display BUT the url does not function as desired.
So basically what I'm asking is how can I get my url to function as desired which is
http://localhost:8000/app/search?q=userTypedInput
AND still have the search results display?
UPDATE
These are my states for ui router
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/home.html', controller: 'homeCtrl'})
.state('search', {
url: '/search?q',
views: {
'' : { templateUrl: 'search/search.html', controller: 'searchCtrl' }
//add more views here when necessary
}
});
searchCtrl
I have this at the top
'use strict';
angular.module("searchApp.search", ['ngAnimate'])
.controller('searchCtrl', ['$scope', '$sce', '$stateParams', '$state', 'searchService', function($scope, $sce, $stateParams, $state, searchService) {
$scope.searchTerms = $stateParams.searchTerms || null;
and this is search(), which contains the $state.go()
$scope.search = function() {
resetResults();
var searchTerms = $scope.searchTerms;
if (searchTerms) {
$scope.results.searchTerms = searchTerms;
} else {
return;
}
getResults();//calls searchService which does the searching
$state.go('search', {q: searchTerms});
};
var getResults = function() {
$scope.isSearching = true;
searchService.search($scope.results.searchTerms,$scope.currentPage,...
I'm trying to get the url to be
http://localhost:8000/app/search?q=userTypedInput
and have the results display as well.
In your state config you use the parameter name of q to pass the search query. This is the name, you also need to use when accessing the parameter from $stateParams in your searchCtrl. In the code shown above, your query will always be null, because you access the parameter named searchQuery which doesn't exist.

How to change template url in angularjs dynamically from controller?

From below angularJS code I want to get parameter namee in templateUrl please help me to generate dynamic templateurl.
sampleApp.config(['$routeProvider',
function($routeProvider){
$routeProvider.
when('/AddNewOrder/:namee', {
controller: 'AddOrderController',
templateUrl:'templates/'+namee +'.html';
}).
when('/ShowOrders/:name', {
templateUrl: 'templates/show_orders.html',
controller: 'ShowOrdersController'
}).
otherwise({
redirectTo: '/AddNewOrder/add_orders'
});
}]);
You can pass a function as a value to templateUrl. The function return value will be the value for templateUrl. Function have access to the url attributes.
Note that the wildcard url name will be the value that you want to access. In your case its namee. console.log(attrs), if you want to see details of the attrs.
$routeProvider.
when('/AddNewOrder/:namee', {
controller: 'AddOrderController',
templateUrl: function(attrs) {
return 'templates/'+ attrs.namee +'.html';
}
})

pass a variable into $routeProvider in angular between views? - angularjs

Wondering if there's an 'angular specific' way to try and achieve this.
I have a page with some views. When a user clicks an anchor, the views change, simple enough. What I'm curious is, if when the user clicks, is it possible to store a variable (say the span) then pass it to the $routeProvider to load the content a bit more dynamically?
so for anchor tag #name1, when that view is displayed, I can pass "name1" into nameHolder as a variable to load some files with same name.
HTML
<span>name1</span>
JS
var nameHolder = [];
var sampleApp = angular.module('sampleApp', ['ngRoute']);
sampleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/' + nameHolder, {
templateUrl: 'templates/individkcd.html',
controller: 'individ',
nameofuser: nameHolder
}).
when('/', {
templateUrl: 'templates/home.html'
});
}]);
sampleApp.controller('individ', function($scope, $route) {
$scope.img = $route.current.nameHolder;
});
Thanks for any info.
UPDATED:
Solution at new thread.
angular js - passing a variable into $routeProvider
You need to add the parameter to your $routeProvider template:
sampleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/' + nameHolder, {
templateUrl: 'templates/individkcd/:nameHolder',
controller: 'individ'
}).
when('/', {
templateUrl: 'templates/home.html'
});
}]);
Then in your target controller use $routeParams:
sampleApp.controller('individ', function($scope, $routeParams) {
$scope.img = $routeParams.nameHolder;
});
From the $routeProvider docs linked above:
path can contain named groups starting with a colon: e.g. :name. All
characters up to the next slash are matched and stored in $routeParams
under the given name when the route matches

$location is not working in Angular

I have an rest api, in which the api is sending instruction to redirect (301 is being sent).
And I have my angular js code like this:
var request = $http.post(LOGIN_URL,{username:'tes',password:'test'})
request.success(function(html)
{
if(html.failure) {
console.log("failure")
$scope.errorMessage = html.failure.message
}
else {
console.log("Success here....")
$location.path("route")
}
})
I can see in the browser log that it is coming in the else part ( Success here..... is being printed). But the url is not changed. $location.path doesnt do anything; I have also tried $location.url which also results the same thing.
And also I'm injecting the $location to my controller.
Where I'm making mistake?
Thanks in advance.
Try something like this
$location.path("/myroute")
You have to have a ng-view on the page as well.
Also make sure you have a corresponding view with that name
and when you're registering your controller you have the '$location' var being injected in the declaration of your controller like this example:
controllers.controller('MyCtrl', ['$scope', '$route', '$location', 'MYService',
function($scope, $route, $location, MyService) {
// ... controller code
}])
also you might want to debug your route changing to see what is happening with a location change listener, like in this example:
return app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'partials/home.html',
controller: 'MyCtrl'
}).
when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
}).
when('/error/:errorId', {
templateUrl: 'partials/error.html',
controller: 'ErrorCtrl'
}).
otherwise({
redirectTo: '/home'
});
}]).run(function($rootScope, $injector, $location) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
console.log('current=' + current.toString());
console.log('next=' + next.toString());
});
});
});

Categories