Angular Select. Add element and automatically select it - javascript

Look ex. jsfiddle example
HTML
<div ng-app="app" ng-controller="mCtrl">
<select size="20" ng-model="selectedType" ng-init="selectedType=types[0]"
ng-options="type.name for type in types">
</select>
<button ng-click="addElem()">add elem in array</button>
</div>
Controller
$scope.types = [ my Array of objects ];
$scope.addElem = function() {
element = {
"id": 999,
"name": "xxx"
};
$scope.types.push(element);
}
I want to add element in ng-options array, and automatically select it in select Box with model changing.
I tried
$scope.selectedType = $scope.types[$scope.types.lenght - 1]
, but it doesn't work.

You have misspelled length.
Here is solution which works:
app = angular.module('app', []);
app.controller('mCtrl', function($scope) {
$scope.types = [
{
"id": 0,
"name": "Zaj"
},
{
"id": 1,
"name": "Emoltra"
},
{
"id": 2,
"name": "Malathion"
},
{
"id": 3,
"name": "Pyramax"
},
{
"id": 4,
"name": "Boink"
},
{
"id": 5,
"name": "Savvy"
},
{
"id": 6,
"name": "Accruex"
},
{
"id": 7,
"name": "Zappix"
}
];
$scope.addElem = function() {
element = {
"id": 7,
"name": "Zappix"
};
$scope.types.push(element);
$scope.selectedType = $scope.types[$scope.types.length - 1];
}
})
DEMO

In your code, there is a typo you have misspelled length
$scope.selectedType = $scope.types[$scope.types.length- 1]
DEMO
OR
You can set it using $scope.selectedType = element
$scope.addElem = function () {
element = {
"id": $scope.types.length + 1,
"name": "Zappix" + $scope.types.length + 1
};
$scope.types.push(element);
$scope.selectedType = element;
}
DEMO

Related

loop and put array within array according to id failed

http://jsfiddle.net/rw0z9e2j/
var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];
var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];
var arr = [],
tempObj = {};
$.each(sports, function (i, obj) {
var sport_id = obj.id;
$.each(playersData, function (i, obj) {
if (sport_id == obj.sport_id) {
tempObj = {
"sport_id": obj.sport_id,
"id": obj.id,
"name": obj.name
};
arr.push(tempObj);
}
});
obj.players = arr;
});
console.log(sports);
I try to build an array of players and put them within sports group according to sport_id but above logic has failed. It didn't group properly, the player who's in sport_id = 1 should go to sport which its id = 1 but why it didn't?
what's wrong with above loop there?
I suppose this is what you want:
var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];
var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];
sports.forEach(function (a) {
var arr = [];
playersData.forEach(function (b) {
if (a.id == b.sport_id) {
arr.push(b);
}
});
a.players = arr;
});
document.write('<pre>' + JSON.stringify(sports, 0, 4) + '</pre>');
You're declaring your temp vars outside of your loops, these should be scoped to your loops and thrown away after each operation.
var arr = [],
tempObj = {};
http://jsfiddle.net/samternent/rw0z9e2j/2/
You have to put it after push:
arr.push(tempObj);
obj.players = arr;
Actually you need this:
var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];
var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];
var arr = [];
$.each(sports, function (i, obj) {
$.each(playersData, function (i, player) {
if (obj.id === player.sport_id) {
var tempObj = {
"sport_id": player.sport_id,
"id": player.id,
"name": player.name
};
arr.push(tempObj);
obj.players = arr;
}
});
});
console.log(sports);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope you want to put inside the Sports group, but you are adding inside the player array, please notice, so please call
obj.sports = arr;
Hope it solve your problem .

filter result using 2 JSON

This is my saved localstorage,
[{"industry_Id":1,"merchant_id":2}]
I want to filter below result, to get HP.
{
"industries": [
{
"id": 1,
"name": "oil and gas",
"merchant": [
{
"id": 1,
"name": "ABC",
},
{
"id": 2,
"name": "DEF",
},
{
"id": 3,
"name": "GHJ",
}
]
},
{
"id": 2,
"name": "IT",
"merchant": [
{
"id": 1,
"name": "Apple",
},
{
"id": 2,
"name": "HP",
},
{
"id": 3,
"name": "Google",
}
]
}
]
}
I thought of using multiple $.each but it have to iterate few times and it's quite redundant.
I would prefer using Javascript for loop, that way you can skip iterating over every object once required element is found.
Without jQuery (using for)
var i, j, merchant = null;
for(i = 0; i < data['industries'].length; i++){
if(data['industries'][i]['id'] == arg[0]['industry_Id']){
for(j = 0; j < data['industries'][i]['merchant'].length; j++){
if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
merchant = data['industries'][i]['merchant'][j];
break;
}
}
if(merchant !== null){ break; }
}
}
With jQuery (using $.each)
var merchant_found = null;
$.each(data['industries'], function(i, industry){
if(industry['id'] == arg[0]['industry_Id']){
$.each(industry['merchant'], function(i, merchant){
if(merchant['id'] == arg[0]['merchant_id']){
merchant_found = merchant;
}
return (!merchant_found);
});
}
return (!merchant_found);
});
var arg = [{"industry_Id":1,"merchant_id":2}];
var data = {
"industries": [
{
"id": 1,
"name": "oil and gas",
"merchant": [
{
"id": 1,
"name": "ABC",
},
{
"id": 2,
"name": "DEF",
},
{
"id": 3,
"name": "GHJ",
}
]
},
{
"id": 2,
"name": "IT",
"merchant": [
{
"id": 1,
"name": "Apple",
},
{
"id": 2,
"name": "HP",
},
{
"id": 3,
"name": "Google",
}
]
}
]
};
var i, j, merchant = null;
for(i = 0; i < data['industries'].length; i++){
if(data['industries'][i]['id'] == arg[0]['industry_Id']){
for(j = 0; j < data['industries'][i]['merchant'].length; j++){
if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
merchant = data['industries'][i]['merchant'][j];
break;
}
}
if(merchant !== null){ break; }
}
}
console.log(merchant);
document.writeln("<b>Without jQuery:</b><br>");
document.writeln((merchant !== null) ? "Found " + merchant['name'] : "Not found");
var merchant_found = null;
$.each(data['industries'], function(i, industry){
if(industry['id'] == arg[0]['industry_Id']){
$.each(industry['merchant'], function(i, merchant){
if(merchant['id'] == arg[0]['merchant_id']){
merchant_found = merchant;
}
return (!merchant_found);
});
}
return (!merchant_found);
});
console.log(merchant_found);
document.writeln("<br><br><b>With jQuery:</b><br>");
document.writeln((merchant_found) ? "Found " + merchant_found['name'] : "Not found");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
selectors.map(function(selector) {
return data.industries.filter(function(industry) {
return industry.id == selector.industry_Id;
})[0].merchant.filter(function(merchant) {
return merchant.id == selector.merchant_id;
})[0].name;
});
// => DEF
If you want "HP", you want industry 2, not industry 1.
.filter(...)[0] is not really optimal. You could use .find(...), but that is not yet universally supported. Or you could use plain old JavaScript and write for loops instead to make it fast. Or you could use objects with ID keys instead of arrays to make lookups faster.
When it comes into a position where collection of data is what you're processing, I suggest you to take a look at underscore.js. It's not optimal choice for the best performance but it does make you code more readable and makes more sense especially when compared with loop.
Say data is a variable which stores your JSON data.
Try this:
// Given this selector criteria
var select = [{"industry_Id":1,"merchant_id":2}];
function filterByCriteria(criteria, data){
var match = [];
_.each(criteria, function(crit){
function matchIndustry(rec){ return rec.id===crit.industry_Id }
function matchMerchant(rec){ return rec.id===crit.merchant_id }
// Filter by industry id
var industry = _.first(_.where(data.industry, matchIndustry));
// Filter by merchant id
var merchant = _.where(industry.merchant, matchMerchant);
_.each(merchant, function addToMatchResult(m){
match.push(m.name);
});
});
return match;
}
var filteredData = filterByCriteria(select, data);
From snippet above, any merchants which match the search criteria will be taken to the match list. Is it more readable to you?
Do you even need numerical id's? Gets super easy when you don't.
/*
{
"industry": {
"oil and gas":{
"merchant": {
"ABC": {
"name": "ABC oil"
},
"DEF": {
"name": "DEF gas"
},
"GHJ" :{
"name": "GHJ oil and gas"
}
}
},
"IT": {
"merchant": {
"Apple" : {
"name": "Apple computers"
},
"HP": {
"name": "Hewlett Packard"
},
"Google": {
"name": "Google. Maw haw haw"
}
}
}
}
}
*/
var data = '{"industry": {"oil and gas":{"merchant": {"ABC": {"name": "ABC oil"},"DEF": {"name": "DEF gas"},"GHJ" :{"name": "GHJ oil and gas"}}},"IT": {"merchant": {"Apple" : {"name": "Apple computers"},"HP": {"name": "Hewlett Packard"},"Google": {"name": "Google. Maw haw haw"}}}}}';
data = JSON.parse(data);
var merchant = data.industry['IT'].merchant['HP'];
alert(merchant.name);
//console.log(merchant.name);

get selected checkbox value in array

I have created an applicaion in angular for getting all the checkbox value which is checked into an array, without any looping, but after simultaneous checking and un-checking i am getting wrong data within the array
Working Demo
can anyone please give me some solution for this
var app = angular.module('checkbox', []);
app.controller('homeCtrl', function ($scope) {
$scope.selected = [];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
"checked": false
}, {
"id": 3,
"value": "orange",
"checked": false
}, {
"id": 5,
"value": "pear",
"checked": false
}];
$scope.checkedOrNot = function (id, isChecked, index) {
if (isChecked) {
$scope.selected.push(id);
} else {
$scope.selected.splice(index, 1);
}
}
});
please see here http://jsfiddle.net/7L6beac6/2/
you need to find index of checkbox in selected array and remove it using that index instead of index of checkbox inside reaper
var app = angular.module('checkbox', []);
app.controller('homeCtrl', function ($scope) {
$scope.selected = [];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
"checked": false
}, {
"id": 3,
"value": "orange",
"checked": false
}, {
"id": 5,
"value": "pear",
"checked": false
}];
$scope.checkedOrNot = function (id, isChecked, index) {
console.log("index:" + index + " " + isChecked);
if (isChecked) {
$scope.selected.push(id);
} else {
var _index = $scope.selected.indexOf(id);
$scope.selected.splice(_index, 1);
}
};
});

how to create elements dynamically in HTML using JSON file

I want to create HTML elements dynamically using JSON file.
{"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
This is my JSON file. i want to create HTML buttons dynamically. Buttons should be create like JAVA,C#,C++. if i add something next to C++ then that button should get created dynamically
You can try something like this FIDDLE
however, i changed the myObject to an array of json objects as follows:
var jsonObj = {"myObject":
[
{
title: 'JAVA',
id: "JAVAsubj",
path: "json/data.json"
},
{
title: "C#",
id: "JAVAsubj",
path: "json/data1.json"
},
{
title: "C++",
id: "JAVAsubj",
path: "json/data2.json"
}
]
}
var count = Object.keys(jsonObj.myObject).length;
var container= document.getElementById('buttons'); // reference to containing elm
for(var i=0;i<count;i++){
var obj= jsonObj.myObject[i];
var button = "<input type='button' value="+obj.title+"></input>"
container.innerHTML+=button;
}
First thing you need to do that get your JSON into js object :
var myJSON= {"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
now get the value of your object into dictionary like below :
var dctLanguages = myJSON["myObject"];
now to render buttons dynamically, just do this :
var strHTML = '';
for (var key in dctLanguages)
{
var language = dctLanguages[key];
strHTML += '<input type="button" id="'+language.id+'" value="'+key+'"/>';
}
and append this HTML into your container div as follows :
$(strHTML).appendTo("#container");
Hope this will work for you..
const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})
This shoule help you
const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})

How can be optimized merging of two arrays of objects?

I would like to optimize my code for CPU and memory consumption. In my function I need to merge two arrays of object into one array. Like UNION, all the ids of the objects in the array have to be unique. I do not want to use third party libraries like Underscore.
This is my function:
var presentation_slides = [
{
"id": "2",
"type": "results"
},
{
"id": "1",
"type": "slide"
},
{
"id": "4",
"type": "questions"
}]
for(var i = 0; i < new_length; i++) {
var my_slide = presentation_slides.filter(function (obj) { return obj.id == i })[0]
if(!my_slide) {
presentation_slides.push({"id": i, "type": "slide"});
}
}
OUTPUT:
var presentation_slides = [
{
"id": "2",
"type": "results"
},
{
"id": "1",
"type": "slide"
},
{
"id": "4",
"type": "questions"
},
{
"id": 0,
"type": "slide"
},
{
"id": 3,
"type": "slide"
}]
Thank you!
EDIT:
Some tests for comparison: http://jsperf.com/how-can-be-optimized-merging-of-two-arrays-of-objects
you can use some instead of filter, i have added a code snipet to your jsperf, which is faster...
check this: .....jsperf.....
for (var i = 0; i < new_length; i++) {
if (!presentation_slides.some(function(obj) { return obj.id == i}))
presentation_slides.push({ "id": i, "type": "slide" });
}
If you just want to merge two arrays, then you can use Array.concat():
var array1 = [
{ id: 1, type: "orange" },
{id: 3, type: "apple" },
{ id: 4, type: "banana" } ],
array2 = [
{ id: 8, type: "strawberry" },
{ id: 9, type: "raspberry" }
];
var array3 = array1.concat(array2);
array3 will contain all the elements from array1 and array2.
This will not check to see if the IDs are unique though.
also, reverse loops are a little faster:
var i = new_length;
while (i--) {
if (!presentation_slides.some(function(obj) { return obj.id == i })) {
presentation_slides.push({ "id": i, "type": "slide" });
}
}
check this ...jspref...

Categories

Resources