AngularJS select default option according to url - javascript

I have a dropdown menu that contains some links for various section of the page. The application is written with AngularJS version 1.4, the dropdown menu does works, but when I enter the page directly through the url in the dropdown menu is always selected the empty voice instead of the correct one. Here' the code:
HTML
<select ng-options="menu_voice.name for menu_voice in menu_voices track by menu_voice.url" ng-model='selectedOption' ng-change="changeLink()">
</select>
JS:
$scope.changeLink = function(){
$state.go($scope.selectedOption.url);
};
$scope.menu_voices = [
{
"url": 'account.company',
"name": 'Company'
},
{
"url": 'account.billing',
"name": 'Billing'
},
{
"url": 'account.password',
"name": 'Password'
},
{
"url": 'account.design',
"name": 'Design'
},
{
"url": 'account.social',
"name": 'Social'
},
{
"url": 'account.notifications',
"name": 'Notifications'
}
];
If I select a voice in the dropdown menu, I go to the correct link with the correct voice selected. But if in the url bar I enter something like:
www.myapp.com/account/billing
I go to the correct page but in the dropdown menu the selected voice is empty.
How can I solve this?
EDIT after first reply:
I added this:
var name = $window.location.pathname;
name = name.substring(9);
name = name.charAt(0).toUpperCase() + name.slice(1);
var url = $window.location.pathname.substring(1).replace(/\//g, '.');
$scope.getSelectedFromUrl = function(){
$scope.selectedOption = {"name": name, "url": url};
};
If I print in the console
console.log($scope.selectedOption);
I get the correct object, e.g:
Object {name: "Design", url: "account.design"}
In the html I simply added the ng-init:
<select ng-options="menu_voice.name for menu_voice in menu_voices track by menu_voice.url" ng-model='selectedOption' ng-change="changeLink()" ng-init="selectedOption = getSelectedFromUrl()">
</select>
But nothing changed.

You could use the ng-init directive to call a function that parses the route and matches it to an item from the voices array. Then set the selectedOption model to that array item, which will set the select option.
ng-init="selectedOption = getSelectedFromURL()"

Related

How to find data from a GET array with parameters already present

Sorry, the title isn't worded very well. I'm using a category choose to choose a category from an API. I currently get the list of categories, filter through their names, and display them in the category chooser. When the user clicks submit, I want the to parse through the API and find the id associated with that category name. Here's an example output from the API:
{
"_id": "5c2fde414502d923ceafaa30",
"title": "Category 2",
"description": "My second category, testing 123",
"createdAt": "2019-01-04T22:29:21.047Z",
"updatedAt": "2019-01-04T22:29:21.047Z",
"__v": 0
},
Here's the code I use for the Category Chooser:
JS:
$.getJSON("http://localhost:2672/categories", function (json) {
$('#category-chooser').empty();
$('#category-chooser').append($('<option>').text("Choose a Category"));
$.each(json, function (i, obj) {
$('#category-chooser').append($('<option>').text(obj.title));
});
});
HTML
<select id="category-chooser" class="form-control" name="category">
<option selected="selected">blank</option>
</select>
If you store the json returned from getJSON somewhere outside the callback, your submit button would fire off something like below:
function getCategoryId(){
const categoryChooser = document.getElementById('category-chooser');
const categorySelected = categoryChooser.value;
json.forEach(entry => {
if(entry.title === categorySelected){
return entry["_id"];
}
});
}

Angular JS: default value in select menu with ng-repeat options

I have tried to follow the examples on the Angular 1.4.12 docs and what I've found here, still I cannot set a default value for a select menu.
My html (using controller as of mob):
<select name="userCurrencyType"
ng-model="mob.currencyType"
ng-options="s.name + ' - ' + s.code for s in mob.currencyTypes"></select>
Which correctly gives me a menu like:
Where my json is an array of objects:
[{ "code": "USD", "name": "United States Dollar" },
{ "code": "GBP", "name": "United Kingdom Pound" }...]
I want the default menu item to be the first item (USD). I have tried setting the ng-model to mob.currencyType and setting this in the controller both like:
_this.currencyType = _this.currencyTypes[0];
and
_this.currencyType = { "code": "USD", "name": "United States Dollar" }
Neither approach gives me a default value set. What am I missing?
UPDATE
After some good suggestions from other users, and some experimenting, it would seem the problem was my data service call was not returning a promise:
_this.currencyTypes = MockDataFactory.query({ filename: 'currency_codes' });
So I added
_this.currencyTypes.$promise.then(function () {
init();
});
And then
function init () {
_this.currencyType = _this.currencyTypes[0];
}
You can set using ng-init
<select ng-model="currency" ng-init="currency='United States Dollar'" ng-options="code.name as code.name for code in currencyTypes">
</select>
DEMO
What you have is fine, just include a track by:
<select name="userCurrencyType"
ng-model="mob.currencyType"
ng-options="s.name + ' - ' + s.code for s in mob.currencyTypes track by s.code"></select>

Angular select and ng-options

I have this angular select:
<select ng-model='obj.status' ng-options='status.code as (status.code + " " + status.phrase) for status in status_codes.data track by status.code'>`
My $scope.status_codes is like this:
data: [
{
"code":"100",
"phrase":"...",
"spec_title":"RFC7231#6.2",
"spec_href":"http://tools.ietf.org/html/rfc7231#section-6.2"
}
...
]
My $scope.obj.status is updated to "300" or "100" or whatever as I change my select, but the select display is always blank. So, the model updates to the selected value of the select input but the input does not show the currently selected value, it shows a blank item.
If i change ng-options to be ng-options='status as (status.code ...' it works, but I only want status.code in my model, not the whole status array. What gives?
I have {{obj | json }} in my HTML and it reads:
obj = {
"name": "",
"description": "",
"payload": "",
"status": "200",
"responseHeaders": {
"entry": [
{
"key": "",
"value": ""
},
{
"key": "",
"value": ""
}
]
}
}
Remove track by.
From the Docs:
Be careful when using select as and track by in the same expression.
My best guess is that the as uses a normal value, like "300", but the track by is using a typed value, like "int:300". Removing one or the other should do it, preferably the track by.
They are giving this as an example:
This will work:
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
but this will not work:
<select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
According to the docs here: https://docs.angularjs.org/api/ng/directive/ngOptions:
select as label for value in array
So in your example this should work (you will get code value as select value in model):
status.code as (status.code + " " + status.phrase) for status in status_codes.data
track by should be used when you have object as value in model, array of objects for options and you want to match current model value to one of objects in array.

Searching in angular.js using id

I have two json:
all_users
"all_users":
{
"4":{
"user_id":4,
"user_name":"Miranda"
},
"7":{
"user_id":7,
"user_name":"seconduser"
}
And tickets
"tickets":
[{
"ticket_id" : 12,
"created_by" : 7,
"assigned_to": 6
}]
Now, from the json tickets, I need to search who created a ticket, i.e created_by. But, since this is id, I am not able to search it directly using name.
After doing my bit of research, I implemented this:
<input id="created-by-input" type="text" ng-model="search.created_by" placeholder="Created by" typeahead="user.user_id as user.user_name for user in transformationFunction(all_users, $viewValue) | filter:{user_name:$viewValue}" class="form-control">
And the scope:
$scope.transformationFunction = function(object) {
var newArray = [];
for(var key in object) {
newArray.push({user_id: key, user_name: object[key].user_name});
}
return newArray;
console.log(newArray)
};
However, when I am searching, I get all the relevant users when I start typing. Also, when I click on them, the search filter works and shows me the result. But, when I click on the users in the dropdown while searching, the text field shows me the ID and not the user name.
For example: I start typing Mira, the dropdown shows Miranda, when I click on it, the text field shows me 4.
What am I missing out in here??
If you would store your users as an array
e.g.
$scope.users = [{
id: 1,
name: "Fancyname"
},
{
id: 2,
name: "Fancyname2"
}]
You could use the .map function like this:
var index = $scope.users.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var user= $scope.users[index];

How to temporary replace div content with another

So the question is in the title. How can I replace one div content with another content for some little time using jQuery? I just have one block with user information that invisible (has display: none; in styles and while info is retrieveing from server I want to display message like Loading user info....
EDIT
Here is how I retrieve information from server:
$.post("/getUserAdditionalInfo",
{ "id": pId },
function (data) {
window.user = $.extend(
{
"pid": pId,
"secondname": data.sname,
"firstname": data.fname,
"middlename": data.mname
}, existingParams);
updateUserInformationLabels();
},
"json"
);
EDIT2
Here is the code I have for user info:
<div id="UserAdditionalInfo">
<ul class="info">
<li><b>First name:</b><span id="ExInfoWorkFirstName"></span></li>
<li><b>Second name:</b><span id="ExInfoWorkSecondName"></span></li>
<li><b>Middle name:</b><span id="ExInfoWorkMiddleName"></span></li>
</ul>
</div>
And I just want to temporarely replace div with id = UserAdditionalInfo with 'loading user info' string. And then data is completely retrieved I need to restore initial content (along replacing place holders with data).
You could do...
$('div:first').html('Loading user info...').load('something.php');
store the original html in a variable like this-
var originalHTMl = $('#UserAdditionalInfo').html();
then replace the content of this div with loading info like this..
$('#UserAdditionalInfo').html('Loading user info...').show();
$.post("/getUserAdditionalInfo",
{ "id": pId },
function (data) {
window.user = $.extend(
{
"pid": pId,
"secondname": data.sname,
"firstname": data.fname,
"middlename": data.mname
}, existingParams);
updateUserInformationLabels(originalHTMl);//pass the original html to this function
var updatedHTML = $('#UserAdditionalInfo').html();// get the updated HTMl
$('#UserAdditionalInfo').html(updatedHTML).show();//Show the div..now this div has all updated htnl
},
"json"
);
function updateUserInformationLabels(originalHTMl){
if (typeof window.patient != 'undefined') {
var ExInfoWork = $(originalHTMl).find('#ExInfoWork');
ExInfoWork.html(window.patient.work);
}
// more replacement logic as you said
}
// don't return anything
}
If You are using jQuery.ajax(), then this is the way :
$.ajax({
beforeSend: function() {
// Replace with "loading..."
},
complete: function() {
// Replace with result
},
});

Categories

Resources