I am getting problem while binding my dropdown value with associative array.
Problem is with track by so like when I don't add track by to my dropdown then I have my binding with dropdown and when I add track by then O am unable to auto select dropdown value.
I want to use track by with ng-options so that angular js doesn't add
$$hashKey and leverage performance benefit associated with track by.
I am not getting why this behaviour is happening.
Note: I only want to bind name of choices like Pizza or burger for each of my $scope.items and not whole object.
Update: As I understand and with so much trying with current data structure of my $scope.items it is not working with ng-options and I want to use ng-options with track by to avoid generating hash key by Angular js. I also tried ng-change as suggested by #MarcinMalinowski but I am getting key as undefined.
So what should be my data structure of $scope.items so that when I need to access any item from my $scope.items? I can access it without doing loop (like we access items from associative array) like how I can access now with correct data structure and using ngoptions only with track by.
var app = angular.module("myApp", []);
app.controller("MyController", function($scope) {
$scope.items = [
{
"title": "1",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc",
"$$hashKey": "object:417"
},
"burger": {
"type": 1,
"arg": "pqr",
"$$hashKey": "object:418"
}
}
},
{
"title": "2",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc",
"$$hashKey": "object:417"
},
"burger": {
"type": 1,
"arg": "pqr",
"$$hashKey": "object:418"
}
}
}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="MyController">
<div ng-repeat="data in items">
<div>{{data.title}}
</div>
<select ng-model="data.myChoice"
ng-options="key as key for (key , value) in data.choices track by $index"><option value="">Select Connection</option></select>
</div>
</ul>
The problems in your code are:
1) track by $index is not supported by ngOptions, it will result the value of the option to be undefined(in your case it will be an $index of ngRepeat);
2) track by doesn't work well with object data-sources (it is supposed to be used with array data-sources), from the docs:
trackexpr: Used when working with an array of objects. The result of
this expression will be used to identify the objects in the array.
Of course, you can use ngRepeat to generate option elements, but personally, I would prefer using ngOptions without track by due to the benefits it has over ngRepeat.
UPDATE: Here is the code that illustrates how you can change your initial data-source and use track by to pre-select an option in case the model is an object. But even in the first example console.log() shows that $$hashKey was not added to choices object.
var app = angular.module("myApp", []);
app.controller("MyController", ['$scope', '$timeout', function($scope, $timeout) {
$scope.items = [
{
"title": "1",
"myChoice" :"burger",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
},
{
"title": "2",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
}
];
$scope.itemsTransformed = angular.copy($scope.items).map(function(item){
delete item.myChoice;
item.choices = Object.keys(item.choices).map(function(choice){
item.choices[choice].name = choice;
return item.choices[choice];
});
return item;
});
//select an option like an object, not a string
$scope.itemsTransformed[1].myChoice = $scope.itemsTransformed[1].choices[0];
$timeout(function() {
//changes a prop in opts array - options are not-re-rendered in the DOM
//the same option is still selected
$scope.itemsTransformed[1].choices[0].arg = "xyz";
}, 3000);
$scope.selectionChanged =function(key, items){
console.log(items); //as we can see $$hashKey wasn't added to choices props
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="MyController">
<p>Without track by:</p>
<div ng-repeat="data in items track by data.title">
<div>{{data.title}} - {{data.myChoice}}</div>
<select ng-model="data.myChoice"
ng-options="key as key for (key , value) in data.choices"
ng-change="selectionChanged(key, items)">
<option value="">Select Connection</option>
</select>
</div>
<hr/>
<p>Using track by name to pre-select an option:</p>
<div ng-repeat="data in itemsTransformed track by data.title">
<div>{{data.title}} - {{data.myChoice}}</div>
<select ng-model="data.myChoice"
ng-options="choice as choice.name for choice in data.choices track by choice.name"
ng-change="selectionChanged(key, itemsTransformed)">
<option value="">Select Connection</option>
</select>
</div>
</ul>
UPDATE 2: A simple example that shows us the fact $$hashKey property is not added to the objects when using ngOptions without track by:
var app = angular.module("myApp", []);
app.controller("MyController", ['$scope', '$timeout', function ($scope, $timeout) {
$scope.items = {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
};
$scope.selectionChanged = function (key, items) {
console.log($scope.items);
};
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<hr/>
<p>Example without track by:</p>
<select ng-model="myChoice"
ng-options="key as key for (key , value) in items"
ng-change="selectionChanged(myChoice, items)">
<option value="">Select Connection</option>
</select>
<hr/>
{{myChoice}}
</div>
UPDATE 3: Final result below (that work with angularjs versions < 1.4, for 1.4+ I would recommend changing the data structure as $scope.itemsTransformed in the first code snippet):
angular.module("myApp", [])
.controller("MyController", ['$scope', function ($scope) {
$scope.items = [
{
"title": "1",
"myChoice": "burger",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
},
{
"title": "2",
"myChoice": "",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
}
];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<div ng-repeat="data in items track by data.title">
<div>{{data.title}} {{data.myChoice}}</div>
<select ng-model="data.myChoice"
ng-options="key as key for (key , value) in data.choices">
<option value="">Select Connection</option>
</select>
</div>
</div>
ngOptions doesn't create new scope like ngRepeat directive per item therefore you don't need to take care about to get rid of $$hashKey
I would use ng-repeat to iterate on <option> (suppose you don't create long lists):
<select ng-model="data.myChoice">
<option value="">Select Connection</option>
<option ng-repeat="(key , value) in data.choices track by key" ng-value="key" title="{{key}}"
>{{key}}</option>
</select>
Working Demo Fiddle
Take look on this issue: github.com/angular/angular.js/issues/6564 - ng-options track by and select as are not compatible
I believe this issue still exists so suggest you to use ngRepeat with track by instead. For small list there is no performance penalty
ngOptions attribute can be used to dynamically generate a list of elements for the element using the array or object
ngModel watches the model by reference, not value. This is important to know when binding the select to a model that is an object or a collection.
1.If you set the model to an object that is equal to an object in your collection, ngOptions won't be able to set the selection, because the objects are not identical. So by default, you should always reference the item in your collection for preselections, e.g.: $scope.selected = $scope.collection[3]
ngOptions will track the identity of the item not by reference, but by the result of the track by expression. For example, if your collection items have an id property, you would track by item.id.
For Example :
$scope.items = [
{
"title": "1",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
},
{
"title": "2",
"myChoice" :"",
"choices": {
"pizza": {
"type": 1,
"arg": "abc"
},
"burger": {
"type": 1,
"arg": "pqr"
}
}
}
];
From the above 2nd point, track the identity of the item not by reference.
Add keyName of key in the object and track by keyName or track by arg , type.
Track by arg or type :
<select ng-model="data.myChoice"
ng-options="choice as choice.arg for choice in data.choices track by choice.arg">
<option value="">Select Connection</option>
</select>
Or add keyName inside the choice object
$scope.items = $scope.items.filter(function(item){
delete item.myChoice;
item.choices = Object.keys(item.choices).map(function(choice){
item.choices[choice].keyName = choice;
return item.choices[choice];
});
return item;
});
HTML Code:
<div ng-controller="MyCtrl">
<ul>
<div ng-repeat="data in items">
<select ng-model="data.selected"
ng-options="choice as choice.keyName for choice in data.choices track by choice.keyName"
ng-change="selection(data.selected)">
<option value="">Select</option>
</select>
</div>
</ul>
</div>
Demo Link Example
You need to add ng-change and pass/use your ng-model value there to get any property you wish.
<select class="form-control pickupaddress ng-pristine ng-valid ng-touched m-r-sm m-t-n-xs" ng-model="item.pickup_address" tabindex="0" aria-invalid="false" ng-options="add._id as add.nick_name for add in addPerFood[item.food._id] | unique:'nick_name'" ng-change="dropDownSelect(item.pickup_address,allCarts,item,$index)">
Related
I am using Angular 1.3.8. I have a select list using an array as options with ngOptions and the syntax includes a basic track by expression.
I need to be able to add unique values to the ID attribute of the options (from that current color's description to the current <option> element when ng-options is creating the option tags. Is there any way to do that? If not, can I use ng-repeat? I have tried ng-repeat with no success.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.colors = [{
"code": "GR",
"description": "Green"
}, {
"code": "RE",
"description": "Red"
}, {
"code": "CY",
"description": "Cyan"
}, {
"code": "MG",
"description": "Magenta"
}, {
"code": "BL",
"description": "Blue"
}];
// Preselect CYAN as default value
$scope.data = {
colorType: $scope.colors[2]
}
});
<script src="https://code.angularjs.org/1.3.8/angular.min.js"></script>
<div ng-app="plunker">
<div ng-controller="MainCtrl">
<strong>ng-options: </strong><select name="color" id="colors" ng-model="data.colorType" ng-options="color as color.description for color in colors track by color.code"></select>
<strong>ng-repeat: </strong><select name="color" id="colors" ng-model="data.colorType">
<option ng-repeat="color in colors" value="{{color}}">{{color.description}}</option>
</select>
<pre>{{ data | json }}</pre>
</div>
</div>
One option is to use ngRepeat with the syntax (key, value) in expression
(key, value) in expression where key and value can be any user defined identifiers, and expression is the scope expression giving the collection to enumerate.
Using that syntax, the key (e.g. index) can be added:
<option ng-repeat="(index, color) in colors" value="{{color}}" id="option_{{index}}">{{color.description}}</option>
See it demonstrated below. Inspecting the options should reveal the id attributes set (e.g. option_0, option_1, etc).
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.colors = [{
"code": "GR",
"description": "Green"
}, {
"code": "RE",
"description": "Red"
}, {
"code": "CY",
"description": "Cyan"
}, {
"code": "MG",
"description": "Magenta"
}, {
"code": "BL",
"description": "Blue"
}];
// Preselect CYAN as default value
$scope.data = {
colorType: $scope.colors[2]
}
});
<script src="https://code.angularjs.org/1.3.8/angular.min.js"></script>
<div ng-app="plunker">
<div ng-controller="MainCtrl">
<strong>ng-repeat: </strong><select name="color" id="colors" ng-model="data.colorType">
<option ng-repeat="(index, color) in colors" value="{{color}}" id="option_{{index}}">{{color.description}}</option>
</select>
<pre>{{ data | json }}</pre>
</div>
</div>
I'm having the angular feature issue where my select list has an empty first option, but this situation is a little different from the research I've done online. When I place the select tag outside of the ng-repeat, there is no blank option as the default selected value. When I place the select tag using the ng-option attribute within the ng-repeat, I have the blank issue. I've tried setting the default value for the ng-model attribute on the select tag with no luck. Here is the html fragment:
<tr ng-repeat="item in todo.items">
<td>{{item.project}}</td>
<td>{{item.action}}</td>
<td>
<select ng-model="ttdSelect" ng-change="moveItem(item.id, ttdSelect);" ng-options="option.name for option in todo.options track by option.name">
</select>
</td>
</tr>
javascript:
var items = [{"id" : 1, "name" : "ttd" , "action" : "do it"}];
var selectOptions = [{ "name" : "next", "value" : "nextUp"},
{ "name" : "in progress", "value" : "inProgress"},
{ "name" : "waiting", "value" : "waiting"},
{ "name" : "done", "value" : "done"},
{ "name" : "trash", "value" : "trash"}];
app.controller("appController", function ($scope)
{
$scope.todo.items = items;
$scope.todo.options = selectOptions;
}
Similar to the answer of jusopi but here in a SO snippet:
var app = angular.module('myApp', []);
var items = [{
"id": 1,
"name": "ttd",
"action": "do it"
},
{
"id": 2,
"name": "zzz",
"action": "do it 2"
}];
var selectOptions = [{
"name": "next",
"value": "nextUp"
}, {
"name": "in progress",
"value": "inProgress"
}, {
"name": "waiting",
"value": "waiting"
}, {
"name": "done",
"value": "done"
}, {
"name": "trash",
"value": "trash"
}];
app.controller("appController", function($scope) {
$scope.todo = {};
$scope.todo.items = items;
$scope.todo.options = selectOptions;
angular.forEach($scope.todo.items, function(item, key) {
item.ttdSelect = $scope.todo.options[0];
});
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="appController">
<div>
<table class="table">
<tr ng-repeat="item in todo.items">
<td>{{item.project}}</td>
<td>{{item.action}}</td>
<td>
<select ng-model="item.ttdSelect"
ng-change="moveItem(item.id, item.ttdSelect);"
ng-options="option.name for option in todo.options track by option.name">
</select>
</td>
</tr>
</table>
<b>Trace:</b>
<pre>
items = {{todo.items | json}}
</pre>
<pre>
options = {{todo.options | json}}
</pre>
</div>
</body>
</html>
I had a hard time following what exactly it is that you wanted so I tried to do it the way I'd normally tackle a problem like this.
example - http://codepen.io/jusopi/pen/PZzxPY
There are a few problems I addressed in reworking your code:
ttdSelect was not pointing to anything in your code. I assumed you meant to update the status value of the todo item so I assigned it to item.status
I created a status option to match a falsy value when a todo item doesn't have a current status
I demonstrated that you can actually bypass ng-options on the <select> and instead use ng-repeat on the <option> element instead to make it a little easier to read.
I hope this helps. Keep in mind I did this in jade/coffeescript because I work faster and better that way. You can easily see the compiled html/js if you need to.
I have a collection as follows:
$scope.TeamType = [
{
"name": "Beginner",
"value": 0
},
{
"name": "Novice",
"value": 1
},
{
"name": "Expert",
"value": 2
},
{
"name": "Masters",
"value": 3
}];
I also have a variable in my controller:
$scope.SelectedTeamType = 0;
I am trying to use these items in the following statement
<select ng-model="SelectedTeamType" ng-options="v as v.name for v in TeamType track by v.value"></select>
I would like the select to init with the corresponding value in the model and save the value to the model when select changes. I am not sure why the model SelectedTeamType is getting the entire object stored to it instead of the v.value and why it isnt initializing with beginner.
As per comment I need to keep $scope.SelectedTeamType as an integer value
Use
<select
ng-model="SelectedTeamType"
ng-options="v.value as v.name for v in TeamType"
></select>
DEMO
Its storing object due to expression which you have provided in ngOptions.
You need to bind object, use
$scope.SelectedTeamType = $scope.TeamType[0];
better
$scope.SelectedTeamType = $scope.TeamType.filter(function(t) {
return t.value == 0;
});
So the overview of the problem; I am retrieving data from an api and creating a CRUD page for it. The data has a set of labels that the user can select.
Below is a code sample representing my problem. The labels selected by the user are represented by the user.labels relationship and the total available labels that can be selected are represented by user.parent.grandparent.labels.
I'm able to sync the selection. What I can't seem to figure out is how to get rid of options that have already been selected from the list of options on any other subsequent select field.
angular.module('app', [])
.controller('select', ['$scope', '$filter', '$location',
function($scope, $filter, $location) {
$scope.user = {
"parent": {
"grandparent": {
"labels": [{
"id": 28,
"name": "Label 1",
}, {
"id": 17,
"name": "Label 2",
}, {
"id": 39,
"name": "Label 3",
}, {
"id": 77,
"name": "Label 4"
}, {
"id": 100,
"name": "Label 5"
}]
}
},
"labels": [{
"id": 28,
"name": "Label 1",
"meta": {
"score": 3
}
}, {
"id": 17,
"name": "Label 2",
"meta": {
"score": 5
}
}]
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="select">
<div ng-repeat="label in user.labels track by $index">
<div class="form-field">
<span>Label</span>
<select ng-model="user.labels[$index]" ng-options="department.name for department
in user.parent.grandparent.labels track by department.id">
</select>
</div>
<div>
<span>Score</span>
<select ng-model="label.meta.score">
<option value="1">1 (lowest)</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5 (highest)</option>
</select>
</div>
</div>
<button ng-click="user.labels.push({})">Add Label</button>
</div>
You can use a filter function inside the ng-repeat to achieve this, here is a sample Codepen showing you how:
http://codepen.io/anon/pen/ZYveOo
You need to pass the filter in the repeat definition:
<select ng-model="user.labels[$index]" ng-options="department.name for department in user.parent.grandparent.labels | filter:removeSelected track by department.id ">
Which refers to this function on scope:
$scope.removeSelected = function(val){
return !_.find($scope.user.labels, function(label) {
return label.id === val.id;
});
};
Even then though I think you are missing one use case which is that you want to be able to have the currently selected label included in the options, by removing all selected options you are removing that ability.
Updated:
Ok then, so after giving this some thought I have come up with the following filter which could be optimised but does seem to work as expected:
.filter('duplicatesFilter', function() {
return function(items, index, selected) {
var res = [selected[index]];
_.forEach(items, function(item){
if(!_.find(selected, function(label) {
return label.id === item.id;
})){
res.push(item);
}
});
return res;
};
})
Use it like so:
<select ng-model="user.labels[$index]" ng-options="department.name for department in user.parent.grandparent.labels | duplicatesFilter:$index:user.labels track by department.id "></select>
This is something I have hit a few times and each time I've worked around it. I'll take a look later if I can find a custom filter that better solves the problem and if I can't I'll tidy up this code and release one; however this should be good to go for your use-case.
Working code-pen:
http://codepen.io/anon/pen/ZYveOo
I am trying to bind data from a web service and then use that data to pre-populate a form. All form controls are binding correctly except for a single multi-select element. If I manually select an option the model does update. Below is my controller:
myApp.controller('AdminVideosEditCtrl', [
'$scope',
'$http',
'$routeParams',
'$location',
function($scope, $http, $routeParams, $location) {
$http.get('/videos/' + $routeParams.videoId + '?embed=presenters').success(function(data) {
$scope.video = data.data
// Load providers
$http.get('/providers').success(function(data) {
$scope.providers = data.data;
// Load Presenters
$http.get('/presenters').success(function(data) {
$scope.presenters = data.data;
});
});
});
}
]);
Once the final request returns, my model looks like this (output via {{ video | json }}):
{
"id": "ca3ca05a-834e-47b1-aaa1-3dbe38338ca9",
"title": "Doloremque iure consequatur quam ea.",
"is_public": false,
"is_visible": true,
"url": "http://someurl.com/",
"provider_id": "1b4d18eb-d56c-41ae-9431-4c058a32d651",
"level_id": "38ed7286-da05-44b9-bfb9-e1278088d229",
"duration": "17:38",
"transcript_file": "rerum-sint-voluptatum.md",
"presenters": [
{
"id": "5111531d-5f2a-45f5-a0c4-4fa3027ff249",
"first_name": "First",
"last_name": "Last",
"full_name": "First Last"
}
],
"provider": {
"id": "1b4d18eb-d56c-41ae-9431-4c058a32d651",
"title": "You Tube"
}
}
Here is how the multi-select looks in my view:
<div class="form-group">
<label for="presenters" class="col-lg-2 control-label">Presenters</label>
<div class="col-lg-10">
<select multiple="multiple" class="form-control" id="presenters" ng-model="video.presenters" ng-options="presenter.full_name for ( id , presenter ) in presenters">
</select>
</div>
</div>
The select element populates correctly, and I would expect for it to default with the "First Last" element selected, however nothing is selected. I know my model is initialized correctly because if I manually select the element nothing in the model changes (if I select a different element it does, but still retains the same structure as it does on initial page load).
I tried adding a $scope.$apply call, and I also tried $scope.$root.$eval(), neither of which worked.
Update
The presenters model (containing all of the presenters) looks like this after it is fetched from the service (names have been changed to protect the innocent):
[
{
"id": "47b6e945-2d4b-44c2-b44b-adb96460864d",
"first_name": "First",
"last_name": "Last",
"full_name": "First Last"
},
{
"id": "5111531d-5f2a-45f5-a0c4-4fa3027ff249",
"first_name": "One",
"last_name": "Two",
"full_name": "One Two"
},
{
"id": "7cb1e44b-2806-4576-80b2-ae730ad356f7",
"first_name": "Three",
"last_name": "Four",
"full_name": "Three Four"
}
]
Solution
Just put this at the bottom of your controller
$scope.video.presenters.forEach(function(obj, idx){
$scope.presenters.forEach(function(presenter, jdx){
if (obj.id === presenter.id) {
$scope.video.presenters = [$scope.presenters[jdx]]
}
});
});
JSFIDDLE
More Robust Solution
This is more robust as you might want to preselect multiple options. This solution pushes each selected option into an array and then assigns it to $scope.video.presenters model
var selectedOptions = [];
$scope.video.presenters.forEach(function (obj, idx) {
$scope.presenters.forEach(function (presenter, idj) {
if (obj.id === presenter.id) {
selectedOptions.push($scope.presenters[idj]);
$scope.video.presenters = selectedOptions;
}
});
JSFIDDLE
Note: Ideally you should be using the id key as the unique for the objects.
This solution assumes and only caters for preselecting one option.