how to make drop-down list dependent using json? - angularjs

Im trying to create a dependent drop-down list box using json.For example: if the car brand selected is "bmw" then the car model drop-down must display only "suv" from the list and other two options shouldn't be displayed.Likewise for "Mercedes" it should display only "suv" and "coupe" in the car model. And also please explain what is the use of json? also how it effect the code.
my.html
Car Brand:
<select name="carname" ng-model="userSelect" required>
<option value="">--Select--</option>
<span ng-show="valdate.carname.$error.required">Car name</span>
<option ng-repeat="ManufactureBrand in a" ng-bind="ManufactureBrand" >
{{ManufactureBrand}}
</option>
</select>
<br/>
<br/> Car Model:
<select name="carmodel" ng-model="selectCar" required>
<option value="">--Select--</option>
<span ng-show="valdate.carmodel.$error.required">Car name</span>
<option ng-repeat="CarName in b" ng-bind="CarName">
{{CarName}}
</option>
</select>
<br/>
<input type="submit" ng-click="checkselection()" ng-disabled="valdate.carname.$invalid && valdate.carmodel.$invalid">
script.js
app.factory('Brandtest', function () {
var brand = {};
brand.sample = ['Bmw', 'Mercedes', 'Honda'];
brand.car = ['Suv', 'Sedan', 'Cope'];
{
return brand;
}
});
app.controller('selectDropdown', ['$scope', 'Brandtest', function ($scope, Brandtest) {
$scope.a = Brandtest.sample;
$scope.b = Brandtest.car;
$scope.list=[];
$scope.carlist=[];
$scope.checkselection = function () {
if ($scope.userSelect != "" && $scope.userSelect != undefined &&
$scope.selectCar != "" && $scope.selectCar != undefined )
{
$scope.list.push($scope.userSelect);
$scope.carlist.push($scope.selectCar);
}
Thanks in advance.

Here is the working plunkr
You have to modified you code as below
your factory should be like this
app.factory('Brandtest', function () {
var brand = {};
brand.sample =[
{
"id": 0,
"carName": "BMW"
},
{
"id": 1,
"carName": "Mercedes"
},
{
"id": 2,
"carName": "Honda"
}
];
brand.car =[
{
"id": 0,
"carType": "Suv",
"parentId": 0
},
{
"id": 1,
"carType": "Sedan",
"parentId": 1
},
{
"id": 2,
"carType": "Cope",
"parentId": 2
}
];
{
return brand;
}
});
In your HTML modify the code like below
<body ng-controller="selectDropdown">
Car Brand:
<select name="carname" ng-model="userSelect" ng-options="p.carName for p in a" required>
<option value="">--Select--</option>
<span ng-show="valdate.carname.$error.required">Car name</span>
</select>
<br/>
<br/> Car Model:
<select name="carmodel" ng-model="selectCar" ng-options="c.carType for c in b | filter:{parentId: userSelect.id}" required>
<option value="">--Select--</option>
<span ng-show="valdate.carmodel.$error.required">Car name</span>
</select>
<br/>
<input type="submit" ng-click="checkselection()" ng-disabled="valdate.carname.$invalid && valdate.carmodel.$invalid">
<table>
<tr>
<th>Car Name</th>
<th>Car Model</th></tr>
<tr ng-repeat="carz in list track by $index">
<td>{{carz.carName}}</td>
<td>{{carlist[$index].carType}}</td>
</tr>
</table>
</body>

You have to maintain some co-relation between the 2 dropdowns. Better would be to have a single json object and use ng-options for populating the second dropdown based on value selected in first dropdown. Run the demo program below and you will get the point.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>Select a car:</h1>
<select ng-model="x" ng-options="x for (x, y) in cars"></select>
<h1 ng-if="x">Category: </h1>
<select ng-if="x" ng-model="y" ng-options="y for y in x"></select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.cars = {
"car01" : ["Ford", "BMW", "NISSAN"],
"car02" : ["Fiat", "Infinity"],
"car03" : ["Volvo", "Toyota"]
}
});
</script>
</body>
</html>

Related

Ng-selected not working angular js 1.6.5

I have tried the following code and failed to get the select option working.
HTML:
<select class=" form-control input-sm" ng-model="formCompletionData.myFilter" ng-change="myFilterChange(formCompletionData.myFilter)">
<option value="">--select--</option>
<option ng-repeat="filter in myfilter" ng-selected="filter.isDefault==true" value="{{filter.filtername}}">{{filter.myfiltername}}</option>
</select>
Angular Code:
$scope.formCompletionData={};
This is the json reponse for $scope.myfilter:
so $scope.myfilter looks like this:
[ {
"_id":"598d8d9998ebb08100fdc272",
"createdBy":"58A559634025FD4867EDAB81",
"myfiltername":"Test",
"filtername":"5A30DA2EB2D0FB046899AED3",
"groupname":"",
"status":"",
"isDefault":true,
"customerId":"SMRTsspd" }, {
"_id":"598da8ec98ebfdceb09d9f4c",
"createdBy":"58A559634025FD4867EDAB81",
"myfiltername":"test2",
"filtername":"5A30DA2EB2D0FB046899AED3",
"groupname":"59DDE8584B28AFFC49E47C89",
"status":"0",
"isDefault":false,
"customerId":"SMRTsspd" }, {
"_id":"598da8fd98ebfdceb09d9f4d",
"createdBy":"58A559634025FD4867EDAB81",
"myfiltername":"test66",
"alluser":false,
"filtername":"594CCAB14B289B198AC85360",
"groupname":"5926C668B7A2B94251CA2EC6",
"status":"1",
"isDefault":false,
"customerId":"SMRTsspd" } ]
In my code below, it is working fine.
angular.module("App", [])
.controller("DemoController", function($scope) {
$scope.formCompletionData = {};
$scope.myfilter = [{
"_id":"598d8d9998ebb08100fdc272",
"createdBy":"58A559634025FD4867EDAB81",
"myfiltername":"Test",
"filtername":"5A30DA2EB2D0FB046899AED3",
"groupname":"",
"status":"",
"isDefault":false,
"customerId":"SMRTsspd" }, {
"_id":"598da8ec98ebfdceb09d9f4c",
"createdBy":"58A559634025FD4867EDAB81",
"myfiltername":"test2",
"filtername":"5A30DA2EB2D0FB046899AED3",
"groupname":"59DDE8584B28AFFC49E47C89",
"status":"0",
"isDefault":false,
"customerId":"SMRTsspd" }, {
"_id":"598da8fd98ebfdceb09d9f4d",
"createdBy":"58A559634025FD4867EDAB81",
"myfiltername":"test66",
"alluser":false,
"filtername":"594CCAB14B289B198AC85360",
"groupname":"5926C668B7A2B94251CA2EC6",
"status":"1",
"isDefault":true,
"customerId":"SMRTsspd"}];
$scope.selectFilter = function(filter) {
$scope.formCompletionData.myFilter=filter;
return true;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="App">
<div ng-controller="DemoController">
<select class="form-control input-sm" ng-model="formCompletionData.myFilter" ng-change="myFilterChange(formCompletionData.myFilter)">
<option value="">--select--</option>
<option ng-repeat="filter in myfilter" ng-selected="filter.isDefault==true && selectFilter(filter.filtername)" value="{{filter.filtername}}">{{filter.myfiltername}}</option>
</select>
</div>
</body>

Angular JS - Select option select option by value id

I has made a ng-repeat of all users but what i want is that he selected current user
<select id="taskUser" class="form-control"
multiple="multiple"
ng-model="taskUser"
ng-options="user.ID as user.Name for user in header.users"
>
</select>
This is my repeater and i show how te list is look like:
<select id="taskUser" class="form-control ng-pristine ng-untouched ng-valid ng-empty" multiple="multiple" ng-model="taskUser" ng-init=" users = header.users[2].id" ng-options="user.ID as user.Name for user in header.users">
<option label="User 1" value="string:1">User 1</option>
<option label="User 2" value="string:2">User 2</option>
<option label="User 3" value="string:3">User 3</option>
</select>
To get the current user id i used {{header.user.ID}} than i get the result just: 3
That means that this need to be selected
<option label="User 3" value="string:3">User 3</option>
$scope.taskUser should be list and defined as [3] because you use multiple
Fiddle Demo
Full code:
function MyCtrl($scope, $timeout) {
$scope.header = {
users:[
{ID: 1, Name: "AAA"},
{ID: 2, Name: "BBB"},
{ID: 3, Name: "CCC"}
]
};
$scope.taskUser = [3];
}
HTML
<select id="taskUser" class="form-control"
multiple="multiple"
ng-model="taskUser"
ng-options="user.ID as user.Name for user in header.users"
>
</select>
<pre>taskUser: {{taskUser|json}}</pre>
You need to define the selected value in an array $scope.taskUser = [3];
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.header = {};
$scope.header.users = [
{ ID: 1, Name: 'John' },
{ ID: 2, Name: 'Rocky' },
{ ID: 3, Name: 'John'},
{ ID: 4, Name: 'Ben' }
];
$scope.taskUser = [3];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<fieldset ng-controller="FirstCtrl">
<select id="taskUser" class="form-control"
multiple="multiple"
ng-model="taskUser"
ng-options="user.ID as user.Name for user in header.users"
></select>
</fieldset>
</div>

eHow to create drop down (grouped) using ng-options?

I have json of all countries with me.
{"countries":[
{"name":"Afghanistan","code":"AF"},
{"name":"Åland Islands","code":"AX"},
{"name":"United States","code":"US"},
{"name":"Canada","code":"CA"},
{"name":"India","code":"IN"}
]};
I want to create drop down like
"
Choose Country(Default)
United States
Canada
------------
Åland Islands
Afghanistan
India
So on..."
I can be achieved via ng-repeat like
<select name="country" id="country" data-ng-model="country" required data-ng-change="allSelect()">
<option value="default" data-ng-data-ng-bind="'Choose Country'"></option>
<option value="{{cList.code}}" data-ng-if="cList.code === 'US'" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
<option value="{{cList.code}}" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
<option value="default1">--------------------------------------------------</option>
<option value="{{cList.code}}" data-ng-if="cList.code !== 'US' && cList.code !== 'CA'" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
</select>
How can i do same via ng-options?
Currently if i want to select any option by default is not happening its creating blank string.
Country list and default values i am getting from different ajax call.
You need to make some changes to your JSON
JSON
{
"Collections": [{
"Name": "North America",
"Countries": [{
"Name": "United States",
"code": "US"
}, {
"Name": "Canada",
"code": "CA"
}
]
}, {
"Name": "Asia",
"Countries": [{
"Name": "India",
"value": "IN"
}
]
}]
}
HTML
<body ng-controller="dobController">
<div class="col-md-20">
<div id="main">
<form class="form-horizontal" role="form">
<label class="control-label col-md-2">Filter List:</label>
<div class="col-md-5">
<select ng-model='theModel' ng-change="display(theModel)">
<optgroup ng-repeat='group in collection' label="{{group.Name}}">
<option ng-repeat='veh in group.Countries' value='{{group.Name}}::{{veh.Name}}'>{{veh.Name}}</option>
</optgroup>
</select>
</div>
</form>
</div>
</div>
Controller
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope", "$http",
function($scope, $http) {
$http.get('test.json').then(function(response) {
$scope.collection = response.data.Collections;
console.log(response);
});
$scope.display = function(name) {
alert(name.split("::")[0] + "." + name.split("::")[1]);
}
}
]);
DEMO

Label value selected in angularJs drop down list

I had a label containing value user.Rules e.g . London
<label id="ruleId" for="Rules" ng-model="user.Rules" ng-hide="editmode"
style="width:97%; word-wrap:break-word; overflow-wrap:break-word;">{{user.Rules }}
</label>
After click on edit button a drop down list appears containing the list of states e,g Delhi, Pune, London etc.,
<select class="form-control" name="user.Rules" data-ng-model="user.Rules" ng-options="option for option in nestedList" ng-show="editmode" style="width:100%; ">
<option value="" style="margin-left:25px">-Select Rule-</option>
</select>
I need to set the selected value as the label value of drop down list i.e. London
How can I do that ?
Since there is no sample code and sample data for nestedList is not available, so I assume the data as my own and created this sample.
I consider the $scope.RuleId contains the id from the database. I removed the ng-model="user.Rules" from the label and and based on the $scope.RuleId I find its equivalent value.
HTML Code:
<div ng-controller="MyCntrl">
<label id="ruleId" for="Rules" ng-hide="editmode"
style="width:97%; word-wrap:break-word; overflow-wrap:break-word;">{{selectedLabel}}
</label>
<select class="form-control" name="ruleDetails" data-ng-model="RuleId"
ng-options="option.RuleId as option.Rules for option in nestedList"
ng-show="editmode" style="width: 100%;">
<option value="" style="margin-left:25px">-Select Rule-</option>
</select>
<div style="height: 10px"></div>
<div>
<button ng-click="editButton()">Edit</button>
</div>
</div>
Controller Code:
function MyCntrl($scope) {
$scope.editmode = false;
$scope.RuleId = "001";
$scope.nestedList = [{
"Rules": "London",
"RuleId": "001"
}, {
"Rules": "Delhi",
"RuleId": "002"
}, {
"Rules": "Pune",
"RuleId": "003"
}, {
"Rules": "Mumbai",
"RuleId": "004"
}, {
"Rules": "Chennai",
"RuleId": "005"
}];
angular.forEach($scope.nestedList, function(rule) {
if (rule.RuleId === $scope.RuleId) {
$scope.selectedLabel = rule.Rules;
}
});
$scope.editButton = function() {
$scope.editmode = true;
};
}
The same code is added in the Working Sample for your reference.

Dynamic Select Boxes in Angular ng-repeat

I'm an old "backender" and pretty new to Angular and modern frontend programming, but I have to learn...
I have the following problem: There is a list with several different person properties, which are created via ng-repeat from Controller response. The values are editable, but the display control depends on the type of the property. The Gender, for example, needs to be edited via a Select-Box. The options for the select box are obtained from a Rest-Server.
So now the main question: How can I build different Select Boxes for each property?
I tried the following code, which is not working:
<section class="contactProperty" ng-repeat="property in contactDetail.properties">
<table>
<tr>
<td>{{property.message}}</td>
<td rowspan=2>{{property.value}}
<script>
var lst = ContactDetailController.getClassification(property.type);
</script>
<input ng-show="{{property.displaystyle_id}}==1" type="text" ng-model="property.value"/>
<select ng-show="{{property.displaystyle_id}}==3" ng-model="property.value">
<option ng-repeat="opt in lst" value="{{opt.id}}">{{opt.message}}</option>
</select>
</td>
</tr>
<tr>
<td>
<select type="text" ng-model="property.status_id">
<option ng-repeat = "status in contactDetail.propertyStatus" value="{{status.id}}">{{status.message}}</option>
</select>
</td>
</tr>
</table>
</section>
The Controller is defined on the top level element with following code
.controller('ContactDetailController',
['$scope', '$rootScope', 'ContactDetailService',
function ($scope, $rootScope, ContactDetailService) {
$scope.getContactDetail = function () {
ContactDetailService.getContactDetail(function(response) {
if(response.success) {
$scope.contactDetail=response;
} else {
$scope.error = response.message;
}
});
};
$scope.getClassifications= function(type) {
ContactDetailService.getClassifications(type, function(response) {
if (response.success) {
return response;
}
});
};
$scope.getContactDetail();
}]);
And the corresponding service:
.factory('ContactDetailService',
['$http', '$rootScope', '$location',
function ($http, $rootScope, $location) {
var service = {};
service.getContactDetail = function(callbackFunc) {
delete $http.defaults.headers.common['X-Requested-With'];
var apiRoot="";
apiRoot = $rootScope.environments[window.location.host];
$rootScope.apiRoot=apiRoot;
var id=$location.search().id;
$http.get(apiRoot+'/contactdetail?id='+id, {})
.success(function(response){
$rootScope.contactDetail=response;
callbackFunc(response);
}).error(function(response){
alert("error"+response.message);
});
};
service.getClassifications = function(type, callbackFunc) {
var apiRoot="";
apiRoot = $rootScope.environments[window.location.host];
$http.get(apiRoot+'/classifications?type='+type, {})
.success(function(response) {
callbackFunc(response);
})
.error(function(response) {
alert("error"+response.message);
});
};
return service;
}]);
Can anyone help me?
you can show/hide fields using ng-show/ng-hide or ng-if or ng-switch depending on your type of variable selected. if this is what you want.
I will try to explain more precisley:
This is a part of my incomming Json from the Backend:
"properties": [
{
"id": 8,
"type_id": 25,
"status_id": 13,
"contact_id": 4,
"value": "27",
"create_date": null,
"update_date": null,
"guikey": "gui.gender",
"message": "Geschlecht",
"displaystyle_id": 3,
"queryparam": "9",
"options": [
{
"id": 26,
"type": 9,
"guikey": "gui.male",
"language": "de",
"message": "Männlich",
"displaystyle_id": 0
},
{
"id": 27,
"type": 9,
"guikey": "gui.female",
"language": "de",
"message": "Weiblich",
"displaystyle_id": 0
}
]
}
],
It is rendered by following code:
<section class="contactProperty" ng-repeat="property in contactDetail.properties">
<table>
<tr>
<td>{{property.message}}</td>
<td rowspan=2 ng-switch on="property.displaystyle_id">{{property.value}}
<input ng-switch-when="1" type="text" ng-model="property.value"/>
<input ng-switch-when="2" type="date" ng-model="property.value"/>
<select ng-switch-when="3" ng-model="property.value">
<option ng-repeat="opt in property.options" value="{{opt.id}}">{{opt.message}}</option>
</select>
</td>
</tr>
<tr>
<td>{{property.status_id}}
<select type="text" ng-model="property.status_id">
<option ng-repeat = "status in contactDetail.propertyStatus" value="{{status.id}}">{{status.message}}</option>
</select>
</td>
</tr>
</table>
</section>
The resulting HTML contains a Select box as expacted:
<section class="contactProperty ng-scope" ng-repeat="property in contactDetail.properties">
<table>
<tbody>
<tr>
<td class="ng-binding">Geschlecht</td>
<td class="ng-binding" on="property.displaystyle_id" ng-switch="" rowspan="2">
27
<select class="ng-scope ng-pristine ng-valid" ng-model="property.value" ng-switch-when="3">
<option class="ng-binding ng-scope" value="26" ng-repeat="opt in property.options">Männlich</option>
<option class="ng-binding ng-scope" value="27" ng-repeat="opt in property.options">Weiblich</option>
</select>
</td>
</tr>
<tr>
</tbody>
</table>
</section>
But the Browser displays the Value "Männlich" in this example, but I expected to see "Weiblich" because the property.value 27 is passed from the json. I just show the value for debug as {{property.value}} and it shows 27, which is correct. I don't understand why the dropdown still showing the first entry (26/Männlich) in this case...

Resources