Using angular ng-select, looking for the best practice/suggestion for linking the select drop-down with the selected option selected based on the properties of an object in scope.
The controller holds an object that (animal) that has a selected cat
The cats (options) are loaded from an Ajax call using any "promise" type angular service ($http in demo)
When the page loads, I want the selected cat to be the same as the animal.cat (would love to see easiest path to bi-directional mapping)
Here is the plunker: http://plnkr.co/edit/bMj7678djgPoJbiTRceG?p=preview
Service/Controller JS.
selectDemo = angular.module('selectDemo',[]);
selectDemo.factory("cat", ["$http", "$log", function($http, $log){
return {
query: function(runAfter){
$log.debug("Getting cats from service");
return $http.get('getCats.json');
}
}
}]);
selectDemo.controller('SelectDemoCtrl', ["$scope", "$log", "cat", function($scope, $log, Cat){
$scope.animal = {type: "Mammal", cat: {"id": 2, "name": "Simon", "breed": "Persian"}};
Cat.query().then(function(data){
cats = data.data;
$scope.cats = cats;
});
}]);
Html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="selectDemo" ng-controller="SelectDemoCtrl">
<h1>AngularJS Select Dropdown</h1>
<div id="data"></div>
<form role="form">
<select data-ng-model="animal.cat" data-ng-options="cat.name for cat in cats">
<option value="">Select a cat</option>
</select>
</form>
<p>You selected: {{ animal.cat }}</p>
</body>
</html>
JSON Response Object:
[{"id": 1, "name": "Garfield", "breed": "Tabby"},
{"id": 2, "name": "Simon", "breed": "Persian"},
{"id": 3, "name": "Twix", "breed": "Mixed"}]
Here's an updated plunk:
http://plnkr.co/edit/KTJt9602eD5Pgr1y7c9w?p=preview
The issue here is that the selected object from the ng-options needs to be reference equal to the object referenced by ng-model, hence the need to find the object in the array.
Related
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)">
I have this code above:
<select ng-model = "vm.modulo.nomenclatura" class="form-control" required>
<option></option>
<option ng-value="modulo.key" ng-repeat="modulo in vm.availableModulos">{{modulo.value}}</option>
</select>
The thing is, the ng-model current value (even before been selected an option), does not shows up on the field. It's blank. Could somebody help?
Thank you
You should be using ng-options instead of repeating the options
Check this fiddle out - https://plnkr.co/edit/XpgXNOPjC9ZJ8lYuPhGP?p=preview
angular.module("sampleApp", [])
.controller("sampleController", function() {
var vm = this;
vm.availableModulos = [
{value: "Value 1"}
{value: "Value 2"},
{value: "Value 3"},
{value: "Value 4"},
{value: "Value 5"}
];
vm.modulo = {nomenclatura: vm.availableModulos[2]};
});
<body data-ng-controller="sampleController as vm">
{{vm.modulo.nomenclatura}}
<select ng-model = "vm.modulo.nomenclatura" class="form-control" required ng-options="mod as mod.value for mod in vm.availableModulos">
<option></option>
</select>
</body>
The best practice in using angular select tag is using ng-options rather than using ng-repeat inside options. Use angular ng-options and track by expression to track your model value. There should be a unique id field that should be provided as track by key. Th ng-model will be initialized on the basis of the track by value.
Here is a working demo.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl as vm">
<select ng-model="vm.modulo.nomenclatura" class="form-control" required ng-options="option.value for option in vm.availableModulos track by option.id"> </select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $timeout) {
var _self = this;
_self.availableModulos = [ { value: "Value 1", id: 0 },
{ value: "Value 2", id: 1 },
{ value: "Value 3", id: 2 },
{ value: "Value 4", id: 3 },
{ value: "Value 5", id: 4 }
];
_self.modulo = {
nomenclatura: _self.availableModulos[2]
};
});
</script>
</body>
</html>
Given the following code:
http://jsfiddle.net/KN9xx/1102/
Suppose I received an ajax call with the following data I pass to a scope variable:
$scope.people_model = {
"people":[
{
"id":"1",
"name":"Jon"
},
{
"id":"2",
"name":"Adam"
}
]
};
How would I work with the select box to iterate over the 'people' via ng-options?
<select
ng-options="p.name for name in people_model"
ng-model="people_model">
</select>
Change your select as ,
<select ng-model="currentSelected" ng-options="selection.id as selection.name for selection in people_model.people"></select>
You need to access the array people inside the object people_model
DEMO
var app = angular.module('myapp', []);
app.controller("FirstCtrl", ["$scope",
function($scope) {
$scope.currentSelected = "1";
$scope.people_model = {
"people": [{
"id": "1",
"name": "Jon"
}, {
"id": "2",
"name": "Adam"
}]
};
}
]);
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="FirstCtrl">
<select ng-model="currentSelected" ng-options="selection.id as selection.name for selection in people_model.people"></select>
</body>
</html>
I want to access the grandparent object of a ng-repeat item in angular.
I am struggling to make this happen.
As you can see from below I want to display the text of the parent object.
This is a watered down version, I am looking for a way to make it work like the top example or a reason as to why it will not work.
Here is the DOM.
<div ng-app ng-controller="MyCtrl">
<!-- this is the one i cannot get working -->
<div>
<div class="copyData" ng-repeat="copy in copyDatabase">
<div ng-repeat="header in masterHeaders">
<div ng-repeat="test in copy.Translations">
set 1: {{test.LanguageAbreviation}}
</div>
</div>
<div>
<!-- this one does work but i need the item from the masterHeaders -->
<div class="copyData" ng-repeat="copy in copyDatabase">
<!-- <div ng-repeat="header in masterHeaders"> -->
<div ng-repeat="test in copy.Translations">
set 2 : {{test.LanguageAbreviation}}
</div>
<!--</div>-->
</div>
</div>
Here is the JSON Object
function MyCtrl($scope) {
$scope.copyDatabase = {
"data": {
"Language": "English",
"Translations": [{
"LanguageID": 308,
"LanguageName": "Arabic - Libya",
"LanguageAbreviation": "ar-LY",
"AvailableLanguages": [{
"ID": 308,
"Name": "Arabic - Libya"
}]
}, {
"LanguageID": 307,
"LanguageName": "Arabic - Egypt",
"LanguageAbreviation": "ar-EG",
"AvailableLanguages": [{
"ID": 307,
"Name": "Arabic - Egypt"
}]
}]
}
}
}
I have also made a JS fiddle for you guys.
http://jsfiddle.net/u7hk0qvj/5/
Seeing your jsfiddle, you have a base mistake, Angular is not finding your MyCtrl. You need to declare as an angular component.
You are creating a global funcion MyCtrl, but this isn't inside the angular context, for example:
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
You can see more info here
Need to have the :
$scope.masterHeaders = {
"home": "home",
"contact": "contact"
}
Object also in the control, If angular does not find the object it will not load any of the DOM elements In the ng-repeat.
Working fiddle
http://jsfiddle.net/u7hk0qvj/8/
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.