jebmarcus jebmarcus - 7 months ago 73
HTML Question

How to append query strings to the URL in Angular ui-router

I am pretty new to AngularJS. I am using ui-router and node.js as my UI server for API calls to another server. Right now, I am having trouble appending query strings to the URL depending on user input (dropdown selections).

My AngularJS controller code:

$scope.getResults = function() {
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};


AngularJS service for the above function:

app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;

return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);


ui-router in Angular:

$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
data:{
pageTitle: 'blah'
}
})


In Node.js, I have my route like this:

app.get("/results", function (req, res) {

var api = 'some api call/' + req.query.color + '/' + req.query.size;

request(api, function (error, response, api) {

if (!error && response.statusCode == 200) {
res.json({
Color: req.query.color,
Size: req.query.size,
Answer: api
});
}
});
});


I want to have the browser url go from /home to /home?color=Red&&size=Large

Obviously I am not doing this right, the browser url is not dynamic right now. Please show how to do this correctly.

Answer

Do use reloadOnSearch: false options to stop reloading current route when changes occurs in state parameters.

$stateProvider.state('home', {
    url: '/home?color&size',
    templateUrl: '/home.html',
    controller: 'MainCtrl',
    data:{ 
       pageTitle: 'blah' 
    },
    reloadOnSearch: false //would not refresh state, for location changes.
})

Controller

$scope.getResults = function() {
    //change parameter of URL usingn $location.search.
    $location.search('color', $scope.myColor);
    $location.search('size', $scope.mySize);
    server.getResults($scope.myColor, $scope.mySize)
    .success(function(data) {
        results = data;
    });
};