how to use ng-options and ng-select with json - javascript

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>

Related

AngularJS: Generate a form dynamically in AngularJS

I am trying to generate a HTML form.
I have an object which contains an array of form elements like
{
"formFields": [
{
"type": "select",
"label": "Fabric",
"name": "fabric",
"options": [
"Georgette",
"Crepe",
"Net",
"Lace"
]
},
{
"type": "text",
"label": "Weight",
"name": "weight",
"options": []
}
]
}
I want to generate a form which has fields in accordance with the above object i.e. it should generate a Select labelled Fabric with drop down options "Georgette","Crepe","Net","Lace" and an input element of type text with label Weight.
What is the best way to do this in AngularJS?
I would make a directive which accepts a form field object as input and $compiles a template based on the input.
Html:
<div my-input="settings"></div>
Js:
angular.module('myApp').directive('myInput', ['$compile', function($compile) {
return {
restrict: 'EA',
require: 'ngModel',
link: linkFn,
scope: {
config: '=myInput'
}
};
function linkFn($scope, $element, $attrs, ngModelCtrl) {
init();
function init() {
$scope.model = {};
var template = getTemplate();
template.attr('ng-model', 'model.value');
$compile(template)($scope, function(clonedElem) {
$element.html(clonedElem);
});
}
function getTemplate() {
switch($scope.config.type) {
case 'text':
return '<input type="text"/>';
case 'select':
return '<input type="select" ng-options="option in config.options">';
}
}
}
}]);
This is from the top of my head so the code might be wrong but you get the idea.
You can refer to the sample here. Please find the code below:
HTML:
<div ng-app="app" ng-controller="test">
<form name="myForm" ng-submit="validateForm(myForm.$valid)">
<div ng-repeat="item in formData.formFields">
<div ng-if="item.type == 'text'">
<label>{{item.label}}: </label>
<input type="{{item.type}}" name="{{item.name}}">
</div>
<div ng-if="item.type == 'select'">
<label>{{item.label}}: </label>
<select name="{{item.name}}">
<option ng-repeat="opt in item.options" value="{{opt}}">{{opt}}</option>
</select>
</div>
<br>
</div>
</form>
</div>
JS:
var app = angular.module('app', []);
app.controller('test', function ($scope) {
$scope.formData = {
"formFields": [
{
"type": "select",
"label": "Fabric",
"name": "fabric",
"options": [
"Georgette",
"Crepe",
"Net",
"Lace"
]
},
{
"type": "text",
"label": "Weight",
"name": "weight",
"options": []
}
]
};
$scope.validateForm = function(isValid){
/*..*/
}
});

Ng-Options in Angular for Arrays and Objects

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>

Bind Json in Knockout

I have to bind the fields "city" of a json type:
{
"italia": [
{
"regione": "Abruzzo",
"capoluoghi": [
{
"citta": "Chieti",
"sigla": "CH"
},
{
"citta": "L'Aquila",
"sigla": "AQ"
},
{
"citta": "Pescara",
"sigla": "PE"
},
{
"citta": "Teramo",
"sigla": "TE"
}
]
},{
"regione": "Basilicata",
"capoluoghi": [
{
"citta": "Matera",
"sigla": "MT"
},
{
"citta": "Potenza",
"sigla": "PZ"
}
]
}, ...
in a 'select' html, via knockout.
I entered the code:
self.provincia = ko.mapping.fromJS([]);
$.getJSON("italia.json", function (data) {
ko.mapping.fromJS(data.italia, {}, self.provincia)
})
and in html:
<div data-bind="with: provincia">
<select class="mm-menu__link" id="Provincia" data-bind:"foreach: capoluoghi">
<option data-bind="text:citta"></option>
</select>
</div>
so as to show all cities, but unfortunately I get nothing!
What did I do wrong?
dave
Tough your question is bit unclear i hope this is what you looking at finally .
view:
<div data-bind="foreach: provincia">
<select class="mm-menu__link" id="Provincia" data-bind="foreach: capoluoghi">
<option data-bind="text:citta"></option>
</select>
</div>
viewModel:
var ViewModel = function () {
var self = this;
self.provincia = ko.observable();
ko.mapping.fromJS(json.italia, {}, self.provincia)
};
ko.applyBindings(new ViewModel());
working sample here
If you want to show all cities in one dropdown check here

angularjs: passing value to custom filter to enable it on dropdown click

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.

How to get the menu key from the json in angularjs

I want the get the "menu1" or "menu2" fields and so on, how to do it in angularjs?
the json is following:
{
"menu1": [
{
"item": "1",
"Auth": "content/articleList",
},
{
"item": "2",
"Auth": "content/articleList",
}],
"menu2": [
{
"item": "3",
"Auth": "publish/cacheSetting",
},
{
"item": "4",
"Auth": "publish/juggleList",
}]
}
You could do like below:
<div ng-repeat="(key, menu) in menus">
{{ key }}
<div ng-repeat="item in menu">
{{item.item}} : {{item.Auth}}
</div>
</div>
If you have a Service and want to use it in a Controller then you'd do the following to load JSON in the service, and call it from a Controller.
App.factory("MenuService", [ '$http', function($http) {
return {
getMenus: function() {
return $http.get( '/menuService' );
}
}
}]);
App.controller("SomeController", ['$scope', 'MenuService', function($scope,MenuService) {
$scope.doSomething = function() {
MenuService.getMenus().success( result ) {
$scope.menu1 = result.menu1;
$scope.menu2 = result.menu2;
// You got menu1 and menu2 now do something
}
}
}]);

Categories

Resources