I have two select dropdowns, the first being the parent of the second. I am able to successfully bind the parent select back to a 'selected item'. But I am unable to bind the child select using ng-model back to the selected parent. I couldn't quite get my example working as I am new to angular but hopefully you get the picture.
$scope.model = {};
$scope.model = {
categories: [{
id: 1,
name: 'Ford',
subCategory: ['focus', 'ranger', 'F150'],
filterValue: ''
}, {
id: 2,
name: 'Honda',
subCategory: ['accord', 'civic', 'pilot'],
filterValue: ''
}],
selectedCategory: {}
}
$scope.categoryChange = function() {
console.dir($scope.selectedCategory);
}
$scope.subCategoryChange = function() {
console.dir($scope.selectedCategory.subCategory);
}
var init = function() {
$scope.model.selectedCategory = $scope.model.categories[0];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<select ng-model="model.selectedCategory" ng-options="category as category.name for category in model.categories" data-ng-change="categoryChange()"></select>
<select ng-model="model.selectedCategory.filterValue" data-ng-options="subCategory for subCategory in model.selectedCategory.subCategory" data-ng-change="subCategoryChange()"></select>
For me it's working!
Maybe you forgot to put ng-app & ng-controller
See This --> Sample
Related
I have two arrays of objects, one array being a subset of the other:
$scope.taskGroups = [
{id: 1, name: 'group1', description: 'description1'},
{id: 2, name: 'group2', description: 'description2'},
{id: 3, name: 'group3', description: 'description3'}
];
$scope.selectedGroups = [
{id: 1, name: 'group1', description: 'description1'},
{id: 2, name: 'group3', description: 'description3'}
];
After unsuccessfully trying to get my head around using ng-option, I thought that I could perhaps create a function to determine if an option should be selected in the select list, based on what I picked up in the documentation:
ngSelected
- directive in module ng Sets the selected attribute on the element, if the expression inside ngSelected is truthy.
So, I came up with this function:
$scope.inSelectedGroups = function(taskGroup) {
angular.forEach($scope.selectedGroups, function(group) {
if (taskGroup.id == group.id) {
return true;
}
return false;
});
};
and tried to use it in this html:
<select multiple ng-model="selectedGroups" style="width: 100%" size="7">
<option ng-repeat="taskGroup in taskGroups" value="{{taskGroup.id}}" ng-selected="inSelectedGroups(taskGroup)">{{taskGroup.name}}</option>
</select>
but, no dice - the full list of taskGroups shows, but the selectedTaskGroups aren't, well, selected...
Am I barking up the wrong tree here?
the full list of taskGroups shows, but the selectedTaskGroups aren't,
well, selected.
I tried your solution which is using the ngSelected attribute but I was unsuccessful as well so I tried using the ngOptions instead and it works.
angular.module('app', []).controller('TestController', ['$scope',
function($scope) {
$scope.taskGroups = [{
id: 1,
name: 'group1',
description: 'description1'
}, {
id: 2,
name: 'group2',
description: 'description2'
}, {
id: 3,
name: 'group3',
description: 'description3'
}];
$scope.selectedGroups = [{
id: 1,
name: 'group1',
description: 'description1'
}, {
id: 2,
name: 'group3',
description: 'description3'
}];
}
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="TestController">
<select multiple="true" ng-model="selectedGroups" style="width: 100%" ng-options="taskGroup.id as taskGroup.description for taskGroup in taskGroups track by taskGroup.id" size="7">
</select>
</div>
See carefully, you are returning Boolean value from function defined in angular.forEach parameter and so nothing is returned from inSelectedGroups function
Try modifying your function to:
$scope.inSelectedGroups = function(taskGroup) {
var flag = false;
angular.forEach($scope.selectedGroups, function(group) {
if (taskGroup.id == group.id) {
flag = true;
return;
}
flag = false;
return;
});
return flag;
};
I am working with angular and semantic ui. I am trying to make a selection of Y and N through a select option. Basically i just want the first item was selected when the page show up. Tried many ways but i couldn't make it works.
Please take a look at this plunker.
angular.module('myapp', [])
.controller('testctrl', function ($scope){
$scope.add = {};
$scope.Consigns = [{value: 'N',label: 'N'}, {value: 'Y',label: 'Y'}];
$scope.add.consign = $scope.Consigns[0].label;
})
.controller('testctrl1', function ($scope){
$scope.add = {};
$scope.Consigns1 = [{value: 'N',label: 'N'}, {value: 'Y',label: 'Y'}];
$scope.add.consign1 = $scope.Consigns1[0].label;
});
https://plnkr.co/edit/cHcLd14xKFxLMS4uy0BM?p=preview
Print the model value in default placeholder. Rather than sending the label value in $scope.add.consign you could send the whole object and print whats required.
Working plunker: https://plnkr.co/edit/XeuiS7p3K1OOx5nHL9c5?p=preview
javascript:
$scope.ListOrder =
[
{ Name: "price", Id: 1 },
{ Name: "exist", Id: 2 },
{ Name: "Sale", Id: 3 },
{ Name: "New", Id: 4 }
];
$scope.Order = { Name: "exist", Id: 1 };
HTML:
<select ng-model="Order" ng-options="obj.Name for obj in ListOrder"></select>
Remove
<script>
$('.ui.dropdown').dropdown();
</script>
and also change select tag to this
<select ng-model="add.consign" class="ui fluid dropdown" ng-options="x.label as x.label for x in Consigns">
<option value=""></option>
</select>
I have hierarchical data set. There is one fixed root unit.
What I want to do is to make this tree browsable with dependent selects.
I have created a simple plunkr example with a fixed dataset.
http://plnkr.co/edit/Bz5A1cbDLmcjoHbs5PID?p=preview
The data format in the example mimics the format I would get from a server request in "real" life.
This working fine in this simple first step. What is missing is, that when a user changes a selection somewhere in the middle, the select boxes and the ng-model binding below the new selection need to be destroyed.
So when I select Europe->France->Quimper and change "Europe" to "Asia" - then there should be "Asia" as the first select box and a second one the Asia countries.
Is there an "Angular" way to deal to deal with this? Any other hint is appreciated also ;)
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://code.angularjs.org/1.3.17/angular.js" data-semver="1.3.17" data-require="angular.js#1.3.17"></script>
</head>
<body>
<div ng-controller="Ctrl">
<select ng-repeat="select in selects track by $index" ng-model="$parent.boxes[$index]">
<option ng-repeat="child in select.children" ng-click="expandSelects(child)">{{child.name}}</option>
</select>
<ul>
<li ng-repeat="item in boxes">{{ item }}</li>
</ul>
</div>
<script>
var app = angular.module('app', []);
app.controller('Ctrl', ['$scope', function($scope) {
var data = {
'europe': {
name: 'europe',
children: [{
name: 'france',
parent: 'europe'
}, {
name: 'italy',
parent: 'europe'
}],
},
'asia': {
name: 'asia',
children: [{
name: 'japan',
parent: 'asia'
}, {
name: 'china',
parent: 'asia'
}],
},
'france': {
name: 'france',
children: [{
name: 'paris',
parent: 'france'
}, {
name: 'quimper',
parent: 'france'
}]
}
};
var root = {
name: 'world',
children: [{
name: 'europe',
parent: 'world'
}, {
name: 'asia',
parent: 'world'
}, ]
};
$scope.selects = [root];
$scope.expandSelects = function(item) {
var select = data[item.name];
if (select) {
$scope.selects.push(select);
}
}
$scope.$watch('boxes', function(item, old) {
}, true);
}]);
</script>
</body>
</html>
This is a classic example of cascading dropdowns, with the added challenge of an unknown number of levels in the cascade. I combined the data set into one object for simplicity, added labels for the dropdowns, and simplified the select element.
This solution allows for any number of levels, so if you needed data below the city level, you could add it without changing any code, as illustrated by the "Street" example I added to Paris.
select {
display: block;
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://code.angularjs.org/1.3.17/angular.js" data-semver="1.3.17" data-require="angular.js#1.3.17"></script>
</head>
<body>
<div ng-controller="Ctrl">
<div ng-repeat="select in selects track by $index" ng-if="select.children">
<label>{{ select.optionType }}</label>
<select ng-model="selects[$index + 1]" ng-options="child.name for child in select.children" ng-change="clearChildren($index)"></select>
<hr />
</div>
</div>
<script>
var app = angular.module('app', []);
app.controller('Ctrl', ['$scope', function($scope) {
var data = {
optionType: 'Continent',
name: 'World',
children: [
{
optionType: 'Country',
name: 'Europe',
children: [
{
optionType: 'City',
name: 'France',
children: [
{
optionType: 'Street',
name: 'Paris',
children: [
{
name: 'First'
},
{
name: 'Second'
}
]
},
{
name: 'Quimper'
}
]
},
{
name: 'Italy'
}
]
},
{
optionType: 'Country',
name: 'Asia',
children: [
{
name: 'Japan'
},
{
name: 'China'
}
]
}
]
};
$scope.selects = [data]
$scope.clearChildren = function (index) {
$scope.selects.length = index + 2;
};
}]);
</script>
</body>
</html>
To go to the children in your hierachy is not as hard as it may seem. If you set up your select with angular and let it do most of the selection for you (for example using ng-options instead of ng-repeating the tag itself), and tell it what options there are, then the list of children you are trying to render just becomes a standard ng-repeat of the children that were picked from the select above.
I modified your plunker to show you how you could accomplish that a slightly different way.
http://plnkr.co/edit/zByFaVKWqAqlR9ulxEBt?p=preview
Main points I changed were
$scope.expandSelects = function() {
var select = data[$scope.selected.name];
if (select) {
console.log('changed');
console.log(select);
$scope.chosen = select;
}
}
Here i just grab the chosen item which the will use. Then the ends up looking like.
<ul>
<li ng-repeat="item in chosen.children">{{ item.name }}</li>
</ul>
The only other set up that was really needed was setting up the with ng-options and giving it a model to bind to.
<select ng-options="child.name for child in selects.children"
ng-model="selected" ng-change="expandSelects()">
</select>
Use can use a filter on the second select to filter de options based on the previous selection.
For example, you can have a first selection to choose the continent:
<select ng-options="c for c in continents" ng-model="selectedContinent" ></select>
and a second selection for the coutries:
<select ng-options="c.name for c in countries | filter : {parent:selectedContinent}" ng-model="selectedCountry" ></select>
Made a fiddle with a simplified data structured just to show how the filter works: http://jsfiddle.net/marcosspn/oarL4n78/
I am using AngularJS directive and I need to set a selected option of a dropdown list in my template.
<select id="energySource" ng-options="o.name for o in energyOptions" ng-model="energy" ng-selected="energy" ng-change="energyChange();"></select>
The content of the optionlist depends on resources send by a server when the page is loaded.
var energyChosen = "All";
angular.element(document).ready(function () {
$.get('/Dashboard/GetResources', function (data) {
scope.Resources = data;
scope.energyOptions = [{ name: scope.Resources.Electricity, id: "Electricity" }, { name: scope.Resources.Gas, id: "Gas" },
{ name: scope.Resources.Water, id: "Water" }, { name: scope.Resources.Solar, id: "Solar" }];
scope.energy = scope.energyOptions[0];
energyChosen = scope.energy.id;
scope.$apply();
});
It works except that a blank option is preselected which disappears when i select an option
I would like to be able to preselect one option. I thought that
scope.energy = scope.energyOptions[0];
would do the trick but it didn't. How can i preselect an option in this case ?
The way you are doing your ng-options it will store the name of the option in scope.energy not the whole option. You were on the right track when you did:
scope.energy = scope.energyOptions[0];
But it won't work because it expects scope.energy to be the name and not the whole option. What you want to do in your ng-options is something like:
<select id="energySource" ng-options="o as on.name for o in energyOptions" ng-model="energy" ng-selected="energy" ng-change="energyChange();"></select>
The important change is the addition of the o as o.name. The 'o' on the left is what will actually be selected and stored in your scope.energy, while the as o.name is the text that will be displayed on your pull down.
Make sure the scope.energy is outside your initialization.
$scope.energyOptions = [
{ name: "test1", id: "Electricity" },
{ name: "test2", id: "Gas" },
{ name: "test3", id: "Water" },
{ name: "test4", id: "Solar" }];
$scope.energy = $scope.energyOptions[2];
http://jsfiddle.net/WcJbu/
When I select a person, I want the favoriteThing selector to display their current selection.
<div ng-controller='MyController'>
<select ng-model='data.selectedPerson' ng-options='person.name for person in data.people'></select>
<span ...> likes </span>
<select ... ng-model='data.favoriteThing' ng-options='thing.name for thing in data.things'></select>
</div>
$scope.data.people = [{
name: 'Tom',
id: 1,
favorite_thing_id: 1
}, {
name: 'Jill',
id: 2,
favorite_thing_id: 3
}];
$scope.data.things = [{
name: 'Snails',
id: 1
}, {
name: 'Puppies',
id: 2
}, {
name: 'Flowers',
id: 3
}];
Do I need to set up a service and add watches, or is there a [good] way to use the favorite_thing_id directly in the select?
Change the second select to this:
<select ng-show='data.selectedPerson' ng-model='data.selectedPerson.favorite_thing_id'
ng-options='thing.id as thing.name for thing in data.things'></select>
Adding the thing.id as to the ng-options will allow you to select the data.things entries based on their id's instead of their references. Changing the ng-model to data.selectedPerson.favorite_thing_id will make angular automatically change to the correct option based on selectedPerson.favorite_thing_id.
jsfiddle: http://jsfiddle.net/bmleite/4Qf63/
http://jsfiddle.net/4Qf63/2/ does what I want - but it's pretty unsatisfying.
$scope.$watch(function() {
return $scope.data.selectedPerson;
}, function(newValue) {
if (newValue) {
$scope.data.thing = $filter('filter')($scope.data.things, {id: newValue.favorite_thing_id})[0];
}
})
I'd like to see all of that be possible from within the select statement.
Maybe I'll try to write a directive.
association = {key: matchValue}
So that I can do
<select ... ng-model='data.thing' ng-options='t.name for t in data.things' association='{id: "data.selectedPerson.favorite_thing_id"}'></select>