Get query string form $location.search() object / Call internal Angular method - angularjs

In Angular, $location.search() returns an object, which is handy to modify: add new params, alter or remove (set to null) existing ones. And $location.search(object) sets this object to the search component of $location. I'm looking for a way to get the composed query string from this object leaving the $location intact. I don't need to get the actual query string, I need to compose the query string from an object.
I don't want to reinvent the wheel and write a javascript function that transforms an object to the string of &-separated key-value pairs, Angular already has one. Basically what I'd like to do is to use toKeyValue method from Angular.js, which is used to compose query string in the $$compose function in location.js. However, it seems like toKeyValue method is inaccessible from outside Angular (unlike, for example, forEach), as I'm getting angular.toKeyValue is not a function error when trying to call it. Is there any way to call toKeyValue method from my controller or just compose the query string from an object by means of Angular?

You can use $httpParamSerializer that converts objects to strings.
This will do from your controller.
app.controller('MainCtrl', function($scope, $httpParamSerializer) {
var querystring = $httpParamSerializer({ width:1680, height:1050 }); //height=1050&width=1680
});

Related

Passing data from ASP.MVC controller to Angular controller Typescript

I have an app that will be started from external app possibly with a parameter (only one) coming with url. I have a following Action inside my MVC Home Controller:
public JsonResult LoadParam()
{
var query = Request.Url.Query.ToString();
string id = HttpUtility.ParseQueryString(query).Get(0);
return Json(id);
}
My problem is how do I call this from angular code? Normally I would use Get, but then I am passing "Home/LoadParam" url and it does not make any sense. I tried passing $location.url(), but then I won't hit LoadParam() action since my single page app stands on Home/Index URL. Not to mention that I couldn't make $location to get me any result (always getting an empty string).
So, to sum up - my question is how do I call this action from angualr code to retrieve the value of parameter when the app is open?
You need to use the $location service to get the query parameters on the client side rather than get it from the server side.
//Access via property
var id = location.search().id;
//Access as array
var id = location.search()[0];
https://docs.angularjs.org/api/ng/service/$location

angular form submit get action append key value pairs

My goal was to have off a form submit for a get to be performed and as part of the uri, key value pairs appended like the following:
// GET /pets/42;q=11;r=22
Reading http://www.w3schools.com/tags/att_form_method.asp
description of form with setting form method to "get" I would have thought this was possible. In the world of angular, it seems like the expected behavior for a submit of a form results in post method. The controller can be written to generate any http verb but has the $http.get doesn't do what plain form get method would automatically and to generate a url like above, the controller would have to build the uri itself.
My apprehension of always using post off a form submit was the form in this case was part of a query/search action and not a data creation exercise. Maybe that's not the proper way to use form but has angular done away with automatically appended values from controls in key value pairs for a form with the $http.get service?
Of course you can do GET with query params in url.
The easiest way is to pass an object representing the key/value pairs to the params property of the $http config object.
var params = {q: 11, r:22};
$.get('/path/to/server/', {params: params}).then(....
Alternatively you can also create your own url string when you only have small number of params.
For further details read through the Usage section of $http docs

What is the correct way to use different `api` with separate query?

I have to make 2 queries or more to get data from the server. for example the first i am getting general information like this:
http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/GetProjectDetails
on user click i need to show the summary of this project. so i need to pass the id to get the data what i requred, the url is :
http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/GetProjectByID/002
But how to make seperate query according to the page?
at present i am using a server.js like this:
(function () {
"use strict";
angular
.module("tcpApp")
.factory("server", ['$resource', function ($resource) {
return $resource('http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/GetProjectDetails');
}]);
})();
$scope.splash = server.query(); //getting json.
It works fine. But how to can update this for both request?
my opinion don't need to get service call,
because your database values already you had.
if $scope.splash have your latest value, then you can get the object by using indexOf().
It's may be no sense. but it is a simple way. else you need call server by using separate query
update:-
I does not mean Seperate Query . I mean you need to pass parameter to the function, if the parameter have any value, then write second query , else you write a first query.
You can get the data from your $scope.splash array by using indexOf() function or map() or some() functions

AngularFire objects

I've been playing with AngularFire, and I understand the documentation for collections. But I feel like I'm totally missing things when it comes to loading specific items inside the collection, by anything besides position in the array.
All of the examples in the Firebase data have pretty names for the api like user/name/first
But when I use angularFireCollection to save a collection I get my object inside a unique $id. (not as pretty)
Is that the expected behavior? And if so, how would I get() an item based on a value instead?
ex. I created a key called slug. That has 'my-theme' in the collection. And I want to load it by $routeParams.
.when('/themes/:slug/', {
templateUrl: 'views/theme.html',
controller: 'ThemesCtrl'
})
How would I load an object into themes/my-theme instead of themes/-J50neNBViK9l7P4QAYc
Thanks in advance...
angularFireCollection automatically creates a list of items with auto-generated incremental IDs (generated by Firebase's push() method). If you want to create a list of items with custom names, angularFire might be a better service to use (it uses set instead of push). For example:
function ThemesCtrl($scope, angularFire) {
$scope.themes = {};
angularFire(new Firebase(URL), $scope, 'themes');
$scope.addTheme = function() {
$scope.themes["my-theme"] = $scope.currentTheme;
}
}

AngularJS custom model objects with methods?

When you have a JSON $resource how can you cast the resulting objects into more specific objects once obtained?
For example, right now they come back as an Array of Objects, but I want them to come back as an Array of "Appointment" objects, so that I can have some methods on that Appointment object which would answer questions about that Appointment object. Ex: Does This Appointment have any services associated with it? Is This appointment in the morning or afternoon?
At first I thought transformResponse hook would work from ngResource, but that doesn't appear to work. The return from that is not the actual objects. Seems that with that function you can only modify the actual data prior to the JSON parsing.
Finally, I question if this is even a proper angularJS technique? Or should these helper methods just show up in a controller or some other module and accept the object to work upon? I just think its cleaner to have them wrapped up in the object, but I admit that I'm not very experienced in angularJS.
If you're using a factory and want to add a function you can for example add the function to the prototype of the returned item (DEMO):
app.factory('Appointment', ['$resource', function($resource) {
var Item = $resource('appointments.json',{/*bindings*/},{/*actions*/});
Item.prototype.hasServices = function() {
if(this.services.length > 0) return true;
else return false;
};
Item.prototype.partOfDay = function() {
if(this.time.split(':')[0] > 12) return "afternoon";
else return "morning";
};
return Item;
}]);
And then access it on your resource in the controller:
$scope.appointments = Appointment.query({}, function() {
console.log($scope.appointments[0].partOfDay())
});
Or directly in the view inside for example an ng-repeat:
{{appointment.partOfDay()}}
To answer your last question, I think the above solution is a proper angularjs technique.
As soon as you have functions associated with a specific resource type it's in my opinion the best to directly append them to the respective resource object. Why should you create helper functions in the controller when you have to pass the resource as a parameter and additionaly the functions may be used in multiple controllers or scopes?!

Resources