I'm trying to figure out why I can't filter the content of the select when dynamically generated from an $http. In the plunker provided I can filter when I provide a test dataset, but when I retrieve the data from an $http request the select does not filter.
http://plnkr.co/edit/lmBRIvfZQogS4LTx2FYV?p=preview
Here is my controller:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('http://graph.facebook.com/4')
.success(function(data) {
$scope.dataset = data;
})
.error(function() {
console.log('My name is Error, now eat it!');
});
// TEST DATASET
// $scope.dataset = [
// {name:'black', shade:'dark'},
// {name:'white', shade:'light'},
// {name:'red', shade:'dark'},
// {name:'blue', shade:'dark'},
// {name:'yellow', shade:'light'}
// ];
});
Here is my HTML:
<body ng-controller="MainCtrl">
Search:
<input type="search" ng-model="searchText" />
<BR>
<BR>
<select>
<option ng-repeat="data in dataset | filter: searchText">{{data}}</option>
</select>
</body>
Filter filters on items in an array. What is being returned from the service is a single object
{ "id": "4", "name": "Mark Zuckerberg", "first_name": "Mark", "last_name": "Zuckerberg", "link": "http://www.facebook.com/zuck", "username": "zuck", "gender": "male", "locale": "en_US" }
This is coming in dropdown because the dropdown also support object properties i think.
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 been following the Angular tutorials, and I am trying to get my JSON data to appear, yet I know I am doing something wrong, but can't figure out the proper method.
I know that somewhere in my app.js my scope is messed up.
How can I display the Family Name of each product?
Here is the layout I have:
app.js
var eloApp = angular.module('eloMicrosite', []);
eloApp.controller('homeListController', ['$scope', '$http',
function($scope, $http) {
$http.get('/Elo/eloMS.min.json')
.success(function(data) {
$scope.products = data;
});
}]);
eloApp.controller('HomeController', function(){
this.products = $scope.products;
});
HTML
<div ng-controller="HomeController as home">
{{home.products[o]["Family Name"]}}
</div>
JSON Layout
{
"products": [
{
"Family Name": "3201L",
"Type": "IDS",
"Size (inches)": 32,
"Aspect Ratio": "16:9",
"Part Number": "E415988",
"Product Description": "ET3201L-8UWA-0-MT-GY-G",
"Marketing Description": "3201L 32-inch wide LCD Monitor",
"Advance Unit Replacement": "",
"Elo Elite": "",
"Package Quantity": 1,
"Minimum Order Quantity": 1,
"List Price": 1800
},
.
.
.
],
"families": [
{
category: "Category1"
},
{
category: "Category2"
}
],
"accessories": [
{
category: "Category1"
},
{
category: "Category2"
}
]
}
You should add homeListController on your page instead of HomeController, Also need to use this instead of using $scope as you wanted to follow controllerAs syntax, 2nd controller is useless in this scenario, you could remove that from app.js.
Markup
<div ng-controller="homeListController as home">
{{home.products[0]["Family Name"]}}
</div>
Controller
eloApp.controller('homeListController', ['$http',
function($http) {
var home = this;
$http.get('/Elo/eloMS.min.json')
.success(function(data) {
home.products = data.products; //products should mapped here
});
}]);
Demo Plunkr
{"id":1,"firstName":"John1","lastName":"Doe1","**accountIds**":[12345,12346,12347],"recipients":[{"accountNumber":22222,"firstName":"Mary1","lastName":"Jane1"},{"accountNumber":33333,"firstName":"Mary2","lastName":"Jane2"}]}
display "accountIds" is dropdown list.
Please see jsfiddle attached http://jsfiddle.net/HB7LU/13213/.
You need to target the accountIds by using dot notation.
HTML
<div ng-controller="MyCtrl">
<select>
<option ng-repeat="item in items.accountIds">{{item}}</option>
</select>
</div>
JS/Angular
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.items = {
"id": 1,
"firstName": "John1",
"lastName": "Doe1",
"accountIds": [12345, 12346, 12347],
"recipients": [{
"accountNumber": 22222,
"firstName": "Mary1",
"lastName": "Jane1"
}, {
"accountNumber": 33333,
"firstName": "Mary2",
"lastName": "Jane2"
}]
}
}
fiddle here http://jsfiddle.net/prantikv/1nvdzv24/9/
i have some uneven data like so
[{
"fname": "Tonja", //common
"lname": "Mize",
"tel": "(963)784-1098",
"address": "3999 Quis Ln",
"city": "Sebring",
"state": "MI",
"zip": 76593
},
{
"fname": "Stella", //common
"Othername": "Lester",
"mobile": "(936)898-2886"
}];
notice only the fname property is common between the two objects
so when i do this
<li ng-repeat="(key,val) in populationList | filter:name">
{{ val.**fname**}}
</li>
i do get the fname but the data is uneven so i cannot figure out how to go through over each object. also the length of the object is different as well.
what i want to do is to filter the data over a select list
<select ng-model="name">
<option value="Tonja" selected="Tonja">Tonja</option>
<option value="Stella">Stella</option>
</select>
but i am unable to figure out a way to display the unmatched properties of objects
is there a way i get all the key:value pairs on the sub data dynamically?
WORKING DEMO
Your Html,
<div ng-app='app'>
<div ng-controller="DemoCtrl">
<select ng-options="item.fname for item in populationList | fieldList:'fname'" ng-model="myItem" ng-change="changeSelection(myItem)">
</select>
<li ng-repeat="key in availableKeys">
{{selectedObject[key]}}
</li>
</div>
</div>
JS
angular.module('filters',[]).
filter('fieldList', function() {
return function(populationList, parameter) {
var filteredArray = [];
angular.forEach(populationList, function(value, index) {
if(value.hasOwnProperty(parameter)) {
filteredArray.push(value);
}
});
return filteredArray;
};
});
angular.module('app',['filters'])
.controller('DemoCtrl', function($scope) {
$scope.changeSelection = function(item) {
$scope.selectedObject = item;
$scope.availableKeys = Object.keys($scope.selectedObject);
};
$scope.populationList = [{
"fname": "Tonja", //common
"lname": "Mize",
"tel": "(963)784-1098",
"address": "3999 Quis Ln",
"city": "Sebring",
"state": "MI",
"zip": 76593
},
{
"fname": "Stella", //common
"Othername": "Lester",
"mobile": "(936)898-2886"
}];
});
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.