angularjs ngRepeat orderBy when property key has spaces - angularjs

I'm getting some data in JSON format which has spaces in the some of the keys:
[
{
"PlainKey": "SomeValue",
"Spaced Key": "SomeValue"
},
{
"PlainKey": "SomeValue2",
"Spaced Key": "SomeValue2"
}
]
This happens at some point:
$http.get('https://dl.dropboxusercontent.com/u/80497/htmlTesting/properties/credits.properties' + '?callback=JSON_CALLBACK').then(function (data) {
$scope.credits = data.data;
}, function (error) {
$scope.errorOccured = true;
console.log("Error:");
console.log(error);
});
and then ng-repeat is used to display it, with ordering:
<select ng-model="corder">
<option value="PlainKey">Plain Key</option>
<option value="Spaced Key">Spaced Key</option>
</select>
<li ng-repeat="credit in credits | orderBy:corder" >
.....
</li>
This doesn't work ( I get an exception )
(The PlainKey works because there are no spaces).
I also tried putting the values in ':
<select ng-model="corder">
<option value="'PlainKey'">Plain Key</option>
<option value="'Spaced Key'">Spaced Key</option>
</select>
This seems to change the order, but not correctly.
What Am I missing?
Thanks!

Simplest way, just surround a field name with UTF8 code for quotation mark:
HTML
<li ng-repeat="item in items | orderBy:'\u0022Spaced Key\u0022'">
JS
$scope.orderKey = '\u0022Spaced Key\u0022';

Comments appeared to help so I'm including it as an answer:
One way to sort items with spaces in their object property names is to pass a predicate sort function into orderBy instead of specifying the object property name. The relevant modifications in particular:
HTML:
<li ng-repeat="credit in credits | orderBy:predicate">
JS:
$scope.predicate = function(val) {
// $scope.corder corresponds to the object property name to sort by
return val[$scope.corder];
}
Demonstration Plunker.

Related

AngularJS - Dropdown Options and Filters

I have two objects, one of users and one of groups. The user object contains the ids of the groups the user is part of, and the groups object contains the id, name and type of group (i.e. hierarchy).
Examples below:
users = {
"user_id_1": {
id: "user_id_1",
name: "Steve Smith",
username: "ssmith1",
groups: ["group_id_1", "group_id_3",...]
},
...
}
groups = {
"group_id_1": {
id: "group_id_1",
name: "Group 1",
type: "level_1"
},
...
}
The goal is (at least initially) to have two dropdowns, one for groups and one for users. Selecting a group filters the user list to only show users part of that group.
I've been looking at ui-select to create the dropdowns for me (the input box as part of the dropdown is ideal) or just simple typeahead (but it does lack the dropdown options).
For now I have a simple example for the users dropdown:
<select id="user-dropdown">
<option ng-repeat="user in $ctrl.users" value="{{ user.id }}">{{ user.name }}</option>
</select>
The problem is that Angular filters only allow filtering of arrays and not objects.
I had the idea of creating two arrays from the objects:
userArray = [user_id_1, user_id_2, ...];
groupArray = [group_id_1, group_id_2, ...];
<option ng-repeat="user in $ctrl.userArray" value="{{ $ctrl.users[user].id }}">{{ $ctrl.users[user].name }}</option>
Even in this case I had problems filtering this list based on the group, as it no longer has the group available in the object.
Any help or thoughts would be appreciated please.
First, reduce your object to an Array and then on select of group dropdown, filter your users. sample code below:
JS:
$scope.groupArray = [];
for(var prop in $scope.groups){
$scope.groupArray.push($scope.groups[prop]);
}
var userArray = [];
for(var prop1 in $scope.users){
userArray.push($scope.users[prop1]);
}
$scope.onGroupSelect = function(){
$scope.userList = [];
$scope.userList = userArray.filter(function(user){
return user.groups.some(function(group){
return group === $scope.selectedGroup;
})
})
}
HTML:
<select ng-model="selectedGroup" ng-change="onGroupSelect()"
ng-options="group.id as group.name for group in groupArray">
</select>
<br/>
<select ng-model="selectedUser">
<option ng-repeat="user in userList" value="user.id">
{{user.name}}
</option>
</select>
here is the working plunkr for your reference

Getting blank value in ng-options angularjs

<select
get-sport
name="sportId"
id="sportId"
ng-model="sm.sport_id"
ng-change="changeSport()"
ng-options="sport.sport_id as sport.name for sport in sports track by sport.sport_id"
ng-required="true">
<option value="" selected="selected">-- Select Sport--</option>
</select>
return {
scope : true,
link : function (scope) {
scope.spinning = true;
$http.get('v1/sport')
.success(success)
.error(error);
function success(data){
scope.sports = data.data;
scope.spinning = false;
}
function error(error) {
console.log(error);
}
}
};
In my console Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object ]
Object having name : cricket, sport_id : '1'
Into my sm.sport_id getting value 3 it should be equal to name : football, sport_id : 3 but by default it is selecting blank value i don't understand why please guide thanks a ton in advance
your answer is here
"you just can't combine value as label for collection with track by. You have to pick the one or the other.".
<select ng-model="sport" ng-options="sport as sport.name for sport in sports track by sport.id">
an in this case you can only get the selected sport as your selected option not the id of that
$scope.sports = [{id: 1, name: 'Cricket'}, {id: 2, name: 'Hockey'}, {id: 3, name: 'Football'}]
$scope.sport = $scope.sports[0];
If you want remove blank in option and dont initialize value for it . Add ng-if in option .
<select
get-sport
name="sportId"
id="sportId"
ng-model="sm.sport_id"
ng-change="changeSport()"
ng-options="sport_id as sport.name for sport in sports track by sport_id"
ng-required="true">
<option value="" ng-if="hideOption" selected="selected">-- Select Sport--</option>
</select>
I overcome this point myself the sport_id need to convert fr4om integer to string i did so it work like a charm

Understanding the filter service from the API docs

The Angular API reference docs uses braces [] when defining the $filter service. What do the braces mean in this context?
{{ expression [| filter_name[:parameter_value] ... ] }}
I think it means optional. However, I've seen code written like this:
<select ng-model="query.level" class="input-medium">
<option selected value="">All</option>
<option selected value="introductory">Introductory</option>
<option selected value="intermediate">Intermediate</option>
<option selected value="advanced">Advanced</option>
</select>
<ul>
<li ng-repeat="session in event.sessions | orderBy:sortorder | limitTo:2 | filter:query">
...
</li>
</ul>
And a controller like
$scope.event = {
sessions: [
{
name: 'Blah',
level: 'Advanced'
},
{
name: 'another thing',
level: 'Intermediate'
}
]
}
query is not a custom or pre-built filter. I fail to see the connection between filter:query and the documentation. Is filter an expression that includes a magic variable somehow initialized simply by it's use in ng-model?
I think the confusion is that filter used in this context does not mean "Angular filter" it actually means filter the list. It's the "filter" filter. The part after the colon in this case is not the name of a filter, but the argument to the "filter" filter.
orderBy is a filter.
limitTo is a filter.
filter is also a filter.
You do not write filter:orderBy or filter:limitTo, you just write orderBy or limitTo. So in the this case, they are writing filter, not filter:filter.
To put it another way, query IS NOT A FILTER. query is the argument to the filter filter, which is included in the list of built-in filters: https://docs.angularjs.org/api/ng/filter
I think that was just bad naming on Angular's part.

Set default value inside ngSelect

I have a a ngSelect with some options in it.
<select data-ng-model="type" data-ng-change="option(type)">
<option data-ng-repeat="type in languages" value="{{type.i18n}}">
{{type.language}}
</option>
</select>
And a Controller
angular.module('navigation', [])
.controller('NavCtrl',['$scope','$translate', function($scope,$translate){
$scope.option = function(type){
console.log(type) //this display the i18n value of languages
$translate.use(type);
}
$scope.languages = [
{ language: "English", i18n: "en_EN"},
{ language: "Swedish", i18n : "se_SE" }
];
}])
I want the ngSelect to have a default option, in my case: "English". I've tried to set it to:
$scope.type = $scope.languages[0].language; // English
$scope.type = $scope.languages[0]; //The whole darn json object.
Help please?
Try this way
<select ng-model="selectedlanguage" ng-change="option(this.selectedlanguage)" ng-options="i.language for i in languages">
</select>
//Js code
angular.module('navigation', [])
.controller('NavCtrl',['$scope','$translate', function($scope,$translate){
$scope.option = function(type){
console.log(type) //this display the i18n value of languages
$translate.use(type);
}
$scope.languages = [
{ language: "English", i18n: "en_EN"},
{ language: "Swedish", i18n : "se_SE" }
];
**$scope.selectedlanguage = $scope.languages[0];**
}])
how about using ngSelected? http://docs.angularjs.org/api/ng/directive/ngSelected
<option ng-selected="$index==0"></option>
or
<option ng-selected="type.language=='English'"></option>
Working example: http://plnkr.co/edit/yv8gew3IDGxjH666UmlC?p=preview
<select data-ng-model="selectedType">
<option data-ng-repeat="lang in languages" value="{{lang.i18n}}">
{{lang.language}}
</option>
</select>
JS:
.controller('NavCtrl',['$scope', function($scope){
$scope.$watch('selectedType', function(type){
if (!type) return;
console.log(type) //this display the i18n value of languages
// $translate.use(type);
});
$scope.languages = [
{ language: "English", i18n: "en_EN"},
{ language: "Swedish", i18n : "se_SE" }
];
$scope.selectedType = $scope.languages[0].i18n;
}]);
Notes:
Have removed the $translate service for ease of reproduction.
Have changed an ng-changed callback to a $watch on the $scope but that is merely aesthetic choice.
The crucial change was that you were choosing the lang.i18n for type but were setting type to lang.language, thus resulting in no matches in the options list.
I don't have enough reputation to comment so I will leave it as an answer.
The Ramesh Rajendran answer is right, but you tried using a different ngOptions syntax.
If you use the label for value in array syntax, then you have to bind the model attribute to the entire object.
If you use the syntax in your comment, which is select as label for value in array then you have to bind the model to the select.
In order words, his example works, and to your example on the comment to work you need to replace $scope.selectedlanguage = $scope.languages[0]; with $scope.selectedlanguage = $scope.languages[0].i18n;
Check the select directive documentation for further information
This worked for me:
$scope.prop = { "values":
[ {name:'hello1',id:1},{name:'hello2',id:2},{name:'hello3',id:3}] };
$scope.selectedValue = 2;
<select ng-model="selectedValue" ng-options="v.id as v.name for v in prop.values">
<option selected value="">Select option</option>
</select>
live example: Plunker

Setting default value in select drop-down using Angularjs

I have an object as below. I have to display this as a drop-down:
var list = [{id:4,name:"abc"},{id:600,name:"def"},{id:200,name:"xyz"}]
In my controller I have a variable that carries a value. This value decided which of the above three items in the array will be selected by default in the drop-down:
$scope.object.setDefault = 600;
When I create a drop-down form item as below:
<select ng-model="object.setDefault" ng-options="r.name for r in list">
I face two problems:
the list is generated as
<option value="0">abc</option>
<option value="1">def</option>
<option value="2">xyz</option>
instead of
<option value="4">abc</option>
<option value="600">def</option>
<option value="200">xyz</option>
No option gets selected by default even though i have ng-model="object.setDefault"
Problem 1:
The generated HTML you're getting is normal. Apparently it's a feature of Angular to be able to use any kind of object as value for a select. Angular does the mapping between the HTML option-value and the value in the ng-model.
Also see Umur's comment in this question: How do I set the value property in AngularJS' ng-options?
Problem 2:
Make sure you're using the following ng-options:
<select ng-model="object.item" ng-options="item.id as item.name for item in list" />
And put this in your controller to select a default value:
object.item = 4
When you use ng-options to populate a select list, it uses the entire object as the selected value, not just the single value you see in the select list. So in your case, you'd need to set
$scope.object.setDefault = {
id:600,
name:"def"
};
or
$scope.object.setDefault = $scope.selectItems[1];
I also recommend just outputting the value of $scope.object.setDefault in your template to see what I'm talking about getting selected.
<pre>{{object.setDefault}}</pre>
In View
<select ng-model="boxmodel"><option ng-repeat="lst in list" value="{{lst.id}}">{{lst.name}}</option></select>
JS:
In side controller
$scope.boxModel = 600;
You can do it with following code(track by),
<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>
This is an old question and you might have got the answer already.
My plnkr explains on my approach to accomplish selecting a default dropdown value. Basically, I have a service which would return the dropdown values [hard coded to test]. I was not able to select the value by default and almost spend a day and finally figured out that I should have set $scope.proofGroupId = "47"; instead of $scope.proofGroupId = 47; in the script.js file. It was my bad and I did not notice that I was setting an integer 47 instead of the string "47". I retained the plnkr as it is just in case if some one would like to see. Hopefully, this would help some one.
<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>
This would get you desired result Dude :) Cheers
Some of the scenarios, object.item would not be loaded or will be undefined.
Use ng-init
<select ng-init="object.item=2" ng-model="object.item"
ng-options="item.id as item.name for item in list"
$scope.item = {
"id": "3",
"name": "ALL",
};
$scope.CategoryLst = [
{ id: '1', name: 'MD' },
{ id: '2', name: 'CRNA' },
{ id: '3', name: 'ALL' }];
<select ng-model="item.id" ng-selected="3" ng-options="i.id as i.name for i in CategoryLst"></select>
we should use name value pair binding values into dropdown.see the
code for more details
function myCtrl($scope) {
$scope.statusTaskList = [
{ name: 'Open', value: '1' },
{ name: 'In Progress', value: '2' },
{ name: 'Complete', value: '3' },
{ name: 'Deleted', value: '4' },
];
$scope.atcStatusTasks = $scope.statusTaskList[0]; // 0 -> Open
}
<select ng-model="atcStatusTasks" ng-options="s.name for s in statusTaskList"></select>
I could help you out with the html:
<option value="">abc</option>
instead of
<option value="4">abc</option>
to set abc as the default value.

Resources