First of all 2 working solutions:
Example 1 - Array in Controller
$scope.s1 = [
{
"name": "Item1",
"id": 1
},
{
"name": "Item2",
"id": 2
}
];
View 1
<select ng-model="select1" ng-options="foo.id as foo.name for foo in s1">
<option value="">Select a Value</option>
</select>
Example 2 - Object in Controller
The same concept may help you also here, if you know the name of "myS2":
$scope.s2 = {
"myS2": [
{
"name" : "Item1",
"id" : 1
},
{
"name": "Item2",
"id": 2
}
]
};
View 2
<select ng-model="select2" ng-options="foo.id as foo.name for foo in s2.myS2">
<option value="">Select a Value</option>
</select>
Now the question:
$scope.s2 has further objects {myS1:[..] to mySn:[..]} with different names and I want'to use them as option group name? How can I do that in ng-options?
I don't think that you can nest loops in ng-repeat, but, adding just a bit of business logic on your controller you can gain what you want!
hope it helps :)
(function(window, angular) {
function TestCtrl(vm, data) {
var options = [];
for(var group in data) {
if(!data.hasOwnProperty(group)) { continue; }
for(var i = 0, len = data[group].length; i < len; i++) {
var item = data[group][i];
item.group = group;
options.push(item);
}
}
vm.options = options;
vm.current = options[0];
}
angular
.module('test', [])
.value('S2', {
"myS2": [
{
"name" : "Item1 mys2",
"id" : 1
},
{
"name": "Item2 mys2",
"id": 2
}
],
"myS3": [
{
"name" : "Item1 mys3",
"id" : 1
},
{
"name": "Item2 mys3",
"id": 2
}
]
})
.controller('TestCtrl', ['$scope', 'S2', TestCtrl])
;
})(window, window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">
<select ng-model="current" ng-options="item as item.name group by item.group for item in options">
</select>
</article>
</section>
Related
I have a data structure like so:
$scope.personalityFields.traveller_type = [
{"id":1,"value":"Rude", "color":"red"},
{"id":2,"value":"Cordial", "color":"yellow"},
{"id":3,"value":"Very Friendly", "color":"green"},
];
And a select box that looks like so:
<select map-value name="traveller_type" ng-init="init_select()" class="full-width" ng-model="traveller_type" ng-options="item as item.value for item in personalityFields.traveller_type">
<option value="" disabled selected> Choose ...</option>
</select>
How do I set the value of the select box to a value based on a response that maps to the "value" field in the attached JSON? Please help !
So if in the response, the traveller_type is field is set to "Rude", I would want the value of "Rude" to be set in the select box.
This what the response looks like:
someObject = {
traveller_type: "Rude"
}
this needs to be displayed on the select box
If you have only value("Rude","Cordial","Friendly") back from response, you have to change ngOptions syntax to be ng-options="item.vaue as item.value for item in personalityFields.traveller_type"(bind item.value to options)
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.traveller_type = 'Rude';
$scope.personalityFields = {
"traveller_type": [{
"id": 1,
"value": "Rude",
"color": "red"
},
{
"id": 2,
"value": "Cordial",
"color": "yellow"
},
{
"id": 3,
"value": "Very Friendly",
"color": "green"
},
]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<select map-value name="traveller_type" class="full-width" ng-model="traveller_type" ng-options="
item.vaue as item.value for item in personalityFields.traveller_type">
<option value="" disabled selected> Choose ...</option>
</select>
{{traveller_type}}
</div>
Else you have entire object({"id":1,"value":"Rude", "color":"red"}) back from response, you have to change ngOptions syntax to be ng-options="item as item.value for item in personalityFields.traveller_type track by item.value"(use track by to only compare value property)
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.traveller_type = {
"id": 1,
"value": "Rude",
"color": "red"
};
$scope.personalityFields = {
"traveller_type": [{
"id": 1,
"value": "Rude",
"color": "red"
},
{
"id": 2,
"value": "Cordial",
"color": "yellow"
},
{
"id": 3,
"value": "Very Friendly",
"color": "green"
},
]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<select map-value name="traveller_type" class="full-width" ng-model="traveller_type" ng-options="
item as item.value for item in personalityFields.traveller_type track by item.value">
<option value="" disabled selected> Choose ...</option>
</select>
{{traveller_type}}
</div>
There are a couple of things wrong with your code, below is an example of you can do to achieve your goal:
angular.module('limitToExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.serverResponse = {
"id": 1,
"value": "Rude",
"color": "red"
};
$scope.personalityFields = {
traveller_type: [{
"id": 1,
"value": "Rude",
"color": "red"
}, {
"id": 2,
"value": "Cordial",
"color": "yellow"
}, {
"id": 3,
"value": "Very Friendly",
"color": "green"
}],
}
}]);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example103-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
</head>
<body ng-app="limitToExample">
<div ng-controller="ExampleController">
<select map-value name="traveller_type" class="full-width" ng-model="serverResponse" ng-options="item as item.value for item in personalityFields.traveller_type track by item.value">
</select>
</div>
</body>
</html>
This is one way of setting the default value, you can make it dynamic based on the response of your server (guess that is what you want?)
I am only replicating what #Pengyy describes in his answer, so feel free to accept his over mine.
I'm trying to filter my ng-repeat through a set of checkboxes which come from a different object. Object 1 holds my categories and object 2 holds all my articles.
The categores object will turn into checkboxes. These checkboxes should act as filter for the articles. An article can have mutliple categories.
$scope.categories:
[
{
"id": "1",
"title": "Blog"
},
{
"id": "2",
"title": "News"
}
]
$scope.articles:
[
{
"id": "1",
"title": "Whats going on",
"categories":{
"results" : [1,2,3]
}
},
{
"id": "2",
"title": "Trump!",
"categories":{
"results" : [3]
}
}
]
Checkboxes:
<div class="filter-pills" ng-repeat="cat in categories">
<input type="checkbox" ng-model="filter[cat.Id]" ng-checked="cat.checked"/>{{cat.Title}}
</div>
ng-repeat:
<div class="col-lg-3 col-md-4" ng-repeat="item in articlesFinal"></div>
I have tried different solutions like ng-change when i update my filter array and compare it to the object used in ng-repeat.
I can't seem to figure this one out. Any suggestions?
Try this
<div class="filter-pills" ng-repeat="cat in categories">
<input type="checkbox" ng-model="cat.checked"/>{{cat.title}}
</div>
<div class="col-lg-3 col-md-4" ng-repeat="item in articles | filter: catFilter">{{item.title}}</div>
and in controller
$scope.catFilter = function (article) {
var checkedCats = vm.categories.filter(function (cat) {
return cat.checked;
});
// no filter, show all
if(checkedCats.length == 0) return true;
for(var i = 0; i < checkedCats.length; i++){
var id = checkedCats[i].id;
if(article.categories.results.indexOf(id) >= 0){
return true;
}
}
// no match, then false
return false
};
Also notice that category id should be integer, not string
$scope.categories = [
{
"id": 1, // integer
"title": "Blog"
},
{
"id": 2,
"title": "News"
}
];
$scope.articles = [
{
"id": "1",
"title": "Whats going on",
"categories":{
"results" : [1,2,3] // integer
}
},
{
"id": "2",
"title": "Trump!",
"categories":{
"results" : [3]
}
}
];
Can somebody explain how to use ng-options when I have below json:
{
"key1":
{
"name":"test1",
"code":"horizontal",
"fields":[
{
"type":"email"
},
{
"type":"text"
}
]
},
"key2":
{
"name":"test2",
"code":"vertical",
"fields":[
{
"type":"emai"
},
{
"type":"text"
}
]
}
}
and then i try to create select like this
<select name="cert" id="cert" ng-options="item as item[paramm] for item in listcert track by $index"></select>
where "paramm" = $key in json.
I want to see something like this
<select>
<option value="horizontal" label='horizontal'>test1</option>
<option value="vertical" label='vertical'>test2</option>
</select>
I have no idea how it works. Please help...
Is this what you were looking for? The trick here is that your data is not in an array format
var data = {
"key1": {
"name":"test1",
"code":"horizontal",
"fields":
[{
"type":"email",
},{
"type":"text",
}]
}, "key2": {
"name":"test2",
"code":"vertical",
"fields":
[{
"type":"emai",
},{
"type":"text",
}]
}
}
angular.module("app", [])
.controller("MainController", MainController);
function MainController() {
var vm = this;
vm.selected = {};
vm.dataArray = [];
angular.forEach(data, function(value, key) {
vm.dataArray.push(value);
}, data);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController as main">
<select ng-options="value as value.code for value in main.dataArray track by value.name" ng-model="selected"></select>
<h3>Selected value:</h3>
<pre>{{selected | json}}</pre>
</div>
this may suits for you
<select>
<option ng-repeat="(key, value) in listcert" value="{{value.code}}" >{{value.name}}</option>
</select>
I have a some data. By default all data should be shown up but when user click on some value in the drop-down then only the filter should start filtering the data.
To do so I am following the below approach.
My filter is like this
filter('myFilter', function() {
return function(data, userInput) {
var filteredArray = [];
// this show whole data
if (true) {/*want to insert enableFilter variable here*/
angular.forEach(data, function(dataobj, key) {
console.log(dataobj);
filteredArray.push(dataobj);
})
}
//this show filtered data
else {
angular.forEach(userInput, function(value, key) {
angular.forEach(data, function(dataobj, key) {
if (dataobj.type.indexOf(value) > -1 && filteredArray.indexOf(dataobj) == -1) {
filteredArray.push(dataobj);
}
})
});
}
return filteredArray;
}
});
To get the user click event I am using ng-change like this
<select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" ng-change=click() multiple>
<option value="classA">Class A</option>
<option value="classB">Class B</option>
<option value="classC">Class C</option>
<option value="classD">Class D</option>
<option value="classE">Class E</option>
Now how can I push the value (i.e. enableFilter) from controller to filter,(I also tried this - Passing arguments to angularjs filters but didn't work ) so that when user click on the drop down then only filter start filtering the data.
My controller is-
angular.module('myapp', [])
.controller('myController', ['$scope', function($scope) {
enableFilter = true;
$scope.enableFilter = true;
/*On user click*/
$scope.click = function() {
console.log("user click");
enableFilter = false;
console.log(enableFilter);
};
$scope.data = {
multipleSelect: []
};
//data
$scope.data = [{
"id": "1",
"type": ["classA", "classB", "classC"],
"name": "Name 1"
}, {
"id": "2",
"type": ["classB", "classC", "classE"],
"name": "Name 2"
}, {
"id": "3",
"type": ["classC"],
"name": "Name 3"
}, {
"id": "4",
"type": ["classD", "classC"],
"name": "Name 4"
}, {
"id": "5",
"type": ["classA", "classB", "classC", "classD", "classE"],
"name": "Name 5"
}];
}])
here is my plunker (http://plnkr.co/edit/QlSe8wYFdRBvK1uM6RY1?p=preview)
if (true) {/*want to insert enableFilter variable here*/
Change true to false for filters codde to work.
The way you wanted :
http://plnkr.co/edit/70jTmSFwtjQ4Nbnb7EVY?p=preview
I have passed a scope param to filter and initially it is set to true and when user selects from the drop down it gets set to false and filter starts applying.
From json i need to update the table based on month and year from javascript.
Any approach is fine for me
For reference i have created the FIDDLEbut it is not complete yet, just want to show the real environment
link: :http://jsfiddle.net/qytdu1zs/1/
HTML
<div class="dropdown">
<select name="one" class="dropdown-select">
<option value="">Select Year</option>
<option value="0">2014</option>
<option value="1">2013</option>
<option value="2">2012</option>
</select>
</div>
<div class="dropdown ">
<select name="two" class="dropdown-select">
<option value="">Select Month</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
</div>
html Table
<div id="example1"></div>
Jquery - i have used mustache.js
$.ajax({
url : 'data/front_finance.json',
dataType : 'json',
success : function (json) {
var customer = $('#example1').columns({
data : json,
schema : [{
"header" : "ID",
"key" : "id",
"template" : "{{id}}"
}, {
"header" : "Name",
"key" : "name",
"template" : '{{name}}'
}, {
"header" : "Actual",
"key" : "actual"
}, {
"header" : "Target",
"key" : "target"
}, {
"header" : "Status",
"key" : "status",
"template" : "<img src ='{{status}}' alt='{{status}}'></img>"
}, {
"header" : "Trend",
"key" : "trend",
"template" : "<img src ='{{trend}}' alt='{{trend}}'></img>"
}
]
});
}
});
JSON
[
{
"year": "2013",
"jan": [
{
"id": 1,
"name": "data",
"actual": "17",
"target": "19",
"status": "red",
"trend": "down"
}
],
"Feb": [
{
"id": 2,
"name": "data1",
"actual": "10",
"target": "19",
"status": "red",
"trend": "down"
}
],
"March": [
{
"id": 3,
"name": "data2",
"actual": "34",
"target": "19",
"status": "green",
"trend": "down"
}
]
},
{
"year": "2014",
"jan": [
{
"id": 1,
"name": "data",
"actual": "17",
"target": "19",
"status": "red",
"trend": "down"
}
],
"Feb": [
{
"id": 2,
"name": "data1",
"actual": "10",
"target": "19",
"status": "red",
"trend": "down"
}
],
"March": [
{
"id": 3,
"name": "data2",
"actual": "34",
"target": "19",
"status": "green",
"trend": "down"
}
]
}
]
NEW FIDDLE FIDDLE
$(document).ready(function (){
cloneObj= $("#example1").clone();
$('select[name=one]').on('change', function() {
var selectedYear=($("option:selected", this).text());
if (selectedYear!="Select Year"){
for (var a in data){
if(data[a].year==selectedYear){
objMonth=data[a];
return false;
}
}
}else{
objMonth=null;
}
});
$('select[name=two]').on('change', function() {
var selectedYear=($("option:selected", $('select[name=one]')).text());
if (selectedYear!="Select Year"){
var selectedMonth=($("option:selected", this).text());
var jsonValue=objMonth[MonthMap[selectedMonth]];
$("#example1").replaceWith(cloneObj.clone());
$('#example1').columns({ data : jsonValue});
}else{
alert("Please Select year please");
}
});
});
I'll give you an approach on how to go about this. Now, I don't know the exact html of your table how the td and tr are structured, so I'm not going to be able to give you exact code that you can replicate.
You let the user select the month and year from the dropdown whose value you can get in jquery. What would help here greatly is if you have the option values set according to the way months are stored in the JSON array.
//JSON array is structured somewhat like:
"jan": [
{
"id": 1,
"name": "data",
"actual": "17",
"target": "19",
"status": "red",
"trend": "down"
}
]
//Your HTML could be
<select name="two" class="dropdown-select">
<option value="">Select Month</option>
<option value="jan">January</option>
<option value="Feb">February</option>
<option value="March">March</option>
Although this is not a necessity, this would greatly help in accessing the corresponding values in the JSON array. Otherwise you would require a mapping of the option values or text to the month names in form of an array or a suitable data structure.
var selectedMonth;
var selectedYear;
//Store the information selected from the dropdown menu for month and year respectively
//Assuming the JSON array is named arr
$.each( arr, function( index, value ) {
if (arr[index]['year'] == selectedYear){
var foo = arr[index]['year'][selectedMonth][0]; //Based on your array defintion
//You can access the required info of this object by simply doing:
//foo.id,foo.name,foo.status etc. and update the relevant table elements' html here
}
});
I hope this gets you started in the right direction.
We have a table ABC. In that table we have a column which contains dropdown as select having value as blank, option a, option b. Now, with change with this dropdown I want to update the input field accordingly, i.e; if a is chosen, input field value will be 100, if b is chosen, input field will be 0 and if blank is chosen, input field will be blank , readonly. The input field id is set to input_ where i is 1 to no of rows in the table.
Below is the code for implementing this.
HTML :
<select id="select" onChange="changeEvent(this.options[this.selectedIndex].value);" name="select">
Javascript:
function changeEvent(chosen) {
var table = document.getElementById("ABC");
var rows = document.querySelectorAll('tr');
var rowsArray = Array.from(rows);
table.addEventListener('change', (event) => {
var target = event.target.toString();
var rowIndex = rowsArray.findIndex(row => row.contains(event.target));
var x = table.rows.length;
var id = "input_"+(parseInt(rowIndex) - 2).toString();
if(chosen === "a") {
table.rows[rowIndex].cells.item(3).innerHTML="<td><input value='100' id='"+id+" 'style='width:50px;'></input></td>";
return;
}else if(chosen === "b"){
table.rows[rowIndex].cells.item(3).innerHTML="<td><input value='0' id='"+id+"' readonly style='width:50px;'></input></td>";
return;
}else{
table.rows[rowIndex].cells.item(3).innerHTML="<td><input value='' id='"+id+"' readonly style='width:50px;'></input></td>";
return;
}
})
}