AngularJS Accessing Value In Querystring - angularjs

Im trying to accessing a value in a querystring.
Here's what i see in the browser:
http://localhost:1010/products/chairs.html?searchMe=testing123
And in my Controller, i have:
var mySearchMeQuery = $location.search().searchMe;
console.log("searchMe = " + mySearchMeQuery );
In my console.log, i am seeing: searchMe = undefined
I have checked i have $location injected in my controller.
** Solution must work in IE8+ **

$location works only if you use path with hash (#). See this.

Use $location.search()
It returns an object key-value pairs; The key is your query string and the value is the query string value.
Example:
function MainCtrl($scope, $location) {
$scope.queryString = $location.search();
// returns {searchMe: "testing123"}
}
And if you want to print the same message as in your question
console.log("searchMe = " + $location.search().searchMe);

You can inject dependecy $routeParams and get the parameter value using something like this:
$routeParams.searchMe
Docs on routeParams
UPDATED Answer:
I have updated an existing fiddle which had $routeParams as an example. If you click on Moby link and check console over there you can see that SearchMe as a querystring is available.
Fiddle

Related

How to set a DropDown List value taken from a promise with a value taken from another promise

I want to understand how to successfully set a value inside a DropDown List after it has been populated by a promise. The value to be set will be taken from another promise which will fill a form with a JSON structure.
In my particular case the incidence is as follows
The Drop-Down List is built as :
1) HTML Template (Jade)
select(name="inputUserRelationship",
ng-model="myForm.relationship",
ng-options="relationshipOption as relationshipOption.value for relationshipOption in relationships track by relationshipOption.id",
ng-init="myForm.insuredRelationship = relationships[0]")
option(value="") -- SELECT --
2) Controller:
$scope.getRelationTypes = function(){
HttpSrv.get('api/getRelationTypes/').then(function(results){
$scope.relationships = results;
}); };
The form gets filled in the Controller as follows:
$scope.getFormInformation = function(ID){
HttpSrv.get('/api/getFormInfo/' + ID).then(function(results){
if(results)
{
$scope.fillForm(results);
}
}); };
$scope.fillForm = function(filledFormData){
$scope.myForm.relationship = filledFormData.relationnshipID; };
This produces the following issues on my JS Debugging Console:
The value gets set on the model
The Drop-Down List stays on the default empty value ([0]).
When I try to change the selected option on my Drop-Down list it then produces the following JS Console Error.
TypeError: Cannot assign to read only property 'id' of 9
at setter (vendor.js:42989)
at Lexer.readIdent.token.fn.extend.assign (vendor.js:42424)
at validationErrorKey.$setViewValue (vendor.js:49629)
at vendor.js:53523
at Scope.promises.$get.Scope.$eval (vendor.js:44729)
at Scope.promises.$get.Scope.$apply (vendor.js:44827)
at HTMLSelectElement. (vendor.js:53465)
at HTMLSelectElement.jQuery.event.dispatch (vendor.js:4641)
at HTMLSelectElement.jQuery.event.add.elemData.handle (vendor.js:4309)
Any information is greatly appreciated. I have already researched & tested the $scope.apply() and $q options and neither have been successful to me even though I know they point to the right direction.
Cheers!
if your $http API call returns an json in the format:
[{"id":"1", "value":"Dropdown desc"}, {...}, {}]
You should set an object literal with the same structure to set the dropdownlist to a specific values like:
$scope.myForm.relationship = {"id":"1", "value":"Dropdown desc"};

Call Angular $filter using expression string

I am trying to call $filter using a filter expression via a filter string I've stored as metadata. For instance my filter string might look like this:
var filterForMyValue = "number : 2 | someOtherFilter";
This would be no problem I was invoking a similar hardcoded filter via markup:
<span>{{ somevalue | number : 2 | someOtherFilter</span>
However I want to programmatically apply this filter. Doing something like this $filter(myFilterString)(valueToFilter) doesn't work since you can't include the filter parameters or multiple chained filters as a single string. It will only allow you to pass the filter name and then the parameters must be passed separately which I don't want since this is a generic method that needs to apply any filter string to a value. I thought $parse might be of some use but I was unable to find any examples of how it might be combined with $filter to achieve this.
This is in the lines of bluetoft comment, maybe one step closer using parser service instead of compile.
http://plnkr.co/edit/ZyFZ42XAuuE4tRZbxKqn?p=preview
$scope.item = 1.123;
//Option 1
var filterFn = $parse('item |number:2|myFilter');
console.log(filterFn($scope));
//Option 2
$scope.item = $filter('number')($scope.item, 2);
$scope.item = $filter('myFilter')($scope.item);
console.log($scope.item);
There are 2 options. Option1 uses parser and option may be you can create custom filter chain service (this is what internally the parser service would do but this is more in terms of your expected pattern of passing input/filters).
I'm not aware of a way to do EXACTLY what you're asking, but I think the $compile service may come of some help going about this in another manor.
var app = angular.module('myApp',[]);
app.filter('myFilter',function(){
return function(val){
return val * 2;
}
});
app.directive('myDirective',function($compile){
return {
restrict:'E',
link: function(scope,element){
scope.filterForMyValue = "number : 2 | myFilter";
scope.item = 1.123;
var format = '<span>{{item |' + scope.filterForMyValue + '}}</span>';
var compiled = $compile(format)(scope);
element.append(compiled);
}
}
});
Plunkr

angular: programmatically format a number using the $locale information

I have included the corresponding locale file and it works fine. In any template I can do things like:
{{ value | number: 2}}
and it correctly formats the number according to the locale info.
Now I need to use the same locale info from javascript code in a controller to build a string.
I'm using a javascript component (a d3 graph to be precise) and I want to build strings to attache to it, so the template system is useless for this, but I'd like to take the locale configuration of numbers and dates from it.
So I'd nee something like this pseudocode:
var formattedValue = $local.format(value, { 'number': 2 });
Or something like that
Anyone knows how can I achieve that?
Try this :
var formattedValue = $filter('number')(value,2);
Working : http://plnkr.co/edit/aC4p95y52YZyoUEdQVzo?p=preview
We can achieve this by implementing a filter.
var app = angular.module('app', []);
app.filter('yourFilter', function(){
return function(string){
// build the string whatever you are trying to achieve
return newString; // return the string you achieved
}
});
for reference, http://blog.trifork.com/2014/04/10/internationalization-with-angularjs/
I could inject the filter like this:
presuApp.run(function ($rootScope, numberFilter) {
var formattedValue = numberFilter(value, 2);
[...]
It's just the name of the filter followed by th 'Filter' suffix.

Values set in a function coming up as undefined in a different state

Using ui-router. take a look at this.
starting with this in the controller:
$scope.transitionResponse = {};
$scope.hello= "world";
transition.makeTransitionCashOutCall(strippedUrl).then(function(response){
//nested view will need this to build out layout
$scope.transitionResponse.OnlineDistributionProcessUrl = response.data.OnlineDistributionProcessUrl;
console.log(response);
console.log($scope.transitionResponse.OnlineDistributionProcessUrl);
if(!response.data.OnlineDistributionProcess){
$scope.showDocument(transitionType);
}else{
//display phone no. if no url
$state.go('rollover-options.cashout-info');
//display url if it exists (same view ^)
}
});
The console.log for $scope.transitionResponse.OnlineDistributionProcessUrl is giving me correct value. But as soon as I drill down to another state the value is lost and i get undefined on console.logs or alerts. What is going on? really? Why is the value set getting lost? I can access hard coded values like $scope.hello fine with {{hello}} in the cashout-info view. But the other value is getting lost. I'm really lost here.
u have not declared OnlineDistributionProcessUrl this field in the json
$scope.transitionResponse = {};
instead it should be like this
$scope.transitionResponse={
"OnlineDistributionProcessUrl":null
}
or you can use
$scope.transitionResponse['OnlineDistributionProcessUrl'] = response.data.OnlineDistributionProcessUrl;

angularjs trying to understand and save a resource state with params

here's the relevant snippet of code:
$scope.submit = function() {
console.log(this);
weekly_habits = $resource('/api/users/:user_id/weekly_habits/:id/', {user_id: '#user'});
entry = weekly_habits.save({name: $scope.newAccomp, count: 0});
$scope.accomplishments.unshift(entry);
$scope.newAccomp = '';
}
my error is that no route matches /api/users/weekly_habits... My project is built in rails and I don't understand what this line means {user_id: '#user'}. Where is this #user object supposed to be? It would be much appreciated if someone explained what's going on here.
Thanks!
From the documentation:
If the parameter value is prefixed with # then the value of that parameter is extracted from the data object (useful for non-GET operations).
And later on they have an example
var User = $resource('/user/:userId', {userId:'#id'});
So the second argument to the resource service are the default parameters. In this case, by default, the userId will be extracted from the resource object you call a method on.
Previously I had an example of a GET operation, which doesn't really make sense in this case. But imagine you were doing a POST ($save) request with a data object. Angular would automatically extract the userId from the data object and inject it into the URL for you. You don't have to manually specify the value for the URL.
More info can be found on the doc page.
http://docs.angularjs.org/api/ngResource.$resource
Quoting the documentation: "If the parameter value is prefixed with # then the value of that parameter is extracted from the data object (useful for non-GET operations)."
The '#user' tells Angular to extract the value of user_id from the 'user' property of the object. So if you call .save() on an object that has an 'user' property of 'abc123', then the :user_id in your URL will be replaced with 'abc123'.

Resources