Get the unique items - Handlebars - javascript

My JSON looks like this:
{
"features": [
{
"id": "belly",
"scenarios": [
{
"id": "belly;a-few-cukes",
"tags": [
{
"name": "#tag1"
}
],
"steps": [
{
"name": "I have 42 cukes in my belly"
},
{
"name": "I wait 1 hour"
},
{
"name": "my belly should growls"
}
]
},
{
"id": "belly;a-few-cukes-with-new-test",
"tags": [
{
"name": "#tag2"
}
],
"steps": [
{
"name": "I have 42 cukes in my belly"
},
{
"name": "I wait 1 hour"
},
{
"name": "my belly should growl"
}
]
}
]
},
{
"id": "newbelly",
"scenarios": [
{
"id": "newbelly;a-few-cukes-with-new-feature",
"tags": [
{
"name": "#tag1"
}
],
"steps": [
{
"name": "I have 42 cukes in my belly"
},
{
"name": "I wait 1 hour"
},
{
"name": "my belly should growls"
}
]
}
]
}
]
}
I would like to retrieve all the unique tag names: i.e., #tag1, #tag2. If you notice, the #tag1 is repeated twice.
My template:
{{#getTags features}}
{{#scenarios}}
{{#tags}}
<p>{{name}}</p>
{{/tags}}
{{/scenarios}}
{{/getTags}}
Custom Helper that I created so far:
Handlebars.registerHelper('getTags', function(context, block) {
var ret = "";
for (var i = 0; i < context.length; i++) {
ret += block.fn(context[i]);
};
return ret;
});
The above custom helper returns all the tags, but I want unique ones.

Something along these lines may work:
Handlebars.registerHelper('getTags', function(context, block) {
var ret = "";
var got = [];
function contains(obj, a) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
for (var i = 0; i < context.length; i++) {
if (!this.contains(context[i],got)) {
got.addObject(context[i]);
ret += block.fn(context[i]);
}
}
return ret;
});
Code used for testing, all javascript:
var ret = "";
var got = [];
var data = ["tag1", "tag1", "tag2", "tag3"]
function contains(obj, a) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
for (var i = 0; i < data.length; i++) {
if (!contains(data[i],got)) {
got.push(data[i]);
ret += data[i];
}
}
console.log( ret);

Related

How to generate a function that, having the array above as input parameter, generates the following output?

given the following array:
[['team1','dep1','tkt1'], ['team2','dep1','tkt2'], ['team2','dep3','tkt75'], ['team2','dep1','tkt10']]
(where the internal array will always have team, dependency, tickets)
• Generate a function that, having the above array as input parameter, generates the following output:
[
{
"dependencies": [
{
"name": "dep1",
"tickets": [
{
"name": "tkt1"
}
]
}
],
"name": "team1"
},
{
"dependencies": [
{
"name": "dep1",
"tickets": [
{
"name": "tkt2"
},
{
"name": "tkt10"
}
]
},
{
"name": "dep3",
"tickets": [
{
"name": "tkt75"
}
]
}
],
"name": "team2"
}
]
You can do something like this
const input = [
["team1", "dep1", "tkt1"],
["team2", "dep1", "tkt2"],
["team2", "dep3", "tkt75"],
["team2", "dep1", "tkt10"],
];
const transform = (data) => {
const teamDepMap = {};
data.forEach(([team, dep, ticket]) => {
if (!teamDepMap[team]) {
teamDepMap[team] = {};
}
if (!teamDepMap[team][dep]) {
teamDepMap[team][dep] = [{name: ticket}];
} else {
teamDepMap[team][dep].push({name: ticket});
}
});
return Object.entries(teamDepMap).map(([team, dependencyMap]) => ({
name: team,
dependencies: Object.entries(dependencyMap).map(([dependency, tickets]) => ({
name: dependency,
tickets
}))
}))
}
console.log(transform(input));
const objectb = [];
function Convertarray(list){
for (let i = 0, len = list.length; i < len; i++) {
let c ={
"dependencies": [
{
"name": list[i][1],
"tickets": [
{
"name": list[i][2]
}
]
}
],
"name": list[i][0]
}
objectb.push(c)
}
return objectb
}
let test=new Convertarray([['team1','dep1','tkt1'], ['team2','dep1','tkt2'], ['team2','dep3','tkt75'], ['team2','dep1','tkt10']])
console.log(test);
const objectb = [];
function Convertarray(list){
for (let i = 0, len = list.length; i < len; i++) {
let c ={
"dependencies": [
{
"name": list[i][1],
"tickets": [
{
"name": list[i][2]
}
]
}
],
"name": list[i][0]
}
objectb.push(c)
}
return objectb
}
let test=new Convertarray([['team1','dep1','tkt1'], ['team2','dep1','tkt2'], ['team2','dep3','tkt75'], ['team2','dep1','tkt10']])
console.log(test);
let myString = JSON.stringify(test);
document.getElementById("result").innerHTML = myString;
<span id="result"></span>

Expand flat object into hierarchical structure

I'm trying to find best approach to expand this flat structure
var input = [
{
"path":"/",
"size":1111
},
{
"path":"/test1",
"size":2222
},
{
"path":"/test1/folder2",
"size":3333
},
{
"path":"/test1/folder2",
"size":4444
},
{
"path":"/test7/folder1",
"size":5555
}
]
into this hierarchical structure
var expectedoutput = [{
"path": "/",
"size": 1111
},
{
"path": "/test1",
"size": 2222,
"items": [{
"path": "/test1/folder2",
"size": 3333,
},
{
"path": "/test1/folder2",
"size": 4444
}
]
},
{
"path": "/test7",
"items": [{
"path": "/test7/folder1",
"size": 5555
}]
}
]
Any ideas? please.
Not so bad approach, it work's but there is one scenario which it cannot handle
Scenario when parent node doesn't exists (should be created) i've commented this part.
Updated version with missing intermediate paths support
function expand_object(list) {
var map = {}, node, roots = [], i;
for (i = 0; i < list.length; i += 1) {
map[list[i].path] = i; // map
list[i].items = []; // place for children
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
//find parent, example "path":"test1/folder2" parent= "test1"
var lastSlash = node.path.lastIndexOf('/');
if (lastSlash > 1) {
lastSlash = lastSlash == -1 ? node.path.length : lastSlash;
parentNode = node.path.substring(0, lastSlash);
}
else {
parentNode = "/";
}
if (parentNode !== "/") {
// creat missing nodes
if (!list[map[parentNode]]) {
list.push({ "name": parentNode ,"path": parentNode, "items": [] })
map[list[list.length-1].path] = list.length-1;
}
var c = list[map[parentNode]];
list[map[parentNode]].items.push(node);
} else {
roots.push(node);
}
}
return roots;
}
var input = [
{
"path":"/",
"size":1111
},
{
"path":"/",
"size":2222
},
{
"path":"/test1",
"size":2222
},
{
"path":"/test1/folder2",
"size":3333
},
{
"path":"/test1/folder2",
"size":4444
}
,
{ //Missing node
"path":"/test7/folder1",
"size":5555
}
]
console.log(expand_object(input));

compare two different arrays in javascript

can any one help in this i am trying to compare two different arrays for pushing values when comparision is equal. below are my two(imageslide.therapy),totalValues arrays and i want compare names like cats and dogs. if condition is true then i need to push their images urls.
var imageslide = {
"therapy": [
{
"name": "cats",
"images": [
{ "url": "cat/firstimg.jpg" },
{ "url": "cat/secondimg.jpg" },
{ "url": "cat/thirdimg.jpg" },
{ "url": "cat/fourthimg.jpg" }
]
},
{
"name": "dogs",
"images": [
{ "url": "dog/firstdog.jpeg" },
{ "url": "dog/seconddog.jpg" },
{ "url": "dog/thirddog.jpg" },
{ "url": "dog/fourthdog.jpg" }
]
},
]
}
var totalValues = ["cats","dogs"];
and i tried like below
var imageArray = imageslide.therapy
function compare(imageArray,totalValues ){
imageArray.forEach((e1)=>totalValues.forEach((e2)=>{
if(e1.name==e2){
console.log(e1.name,",",e2)
}
})
For what I understand from your question here is the answer. Please forgive me I don't know much about arrow function so I wrote it in simple javascript.
var imageslide = {
"therapy": [
{
"name": "cats",
"images": [
{ "url": "cat/firstimg.jpg" },
{ "url": "cat/secondimg.jpg" },
{ "url": "cat/thirdimg.jpg" },
{ "url": "cat/fourthimg.jpg" }
]
},
{
"name": "dogs",
"images": [
{ "url": "dog/firstdog.jpeg" },
{ "url": "dog/seconddog.jpg" },
{ "url": "dog/thirddog.jpg" },
{ "url": "dog/fourthdog.jpg" }
]
},
]
}
var totalValues = ["cats","dogs"];
var imageArray = imageslide.therapy
function compare(imageArray,totalValues ){
for(var i=0;i<imageArray.length;i++){
for(var j=0;j<totalValues.length;j++){
if(totalValues[j]=imageArray[i].name){
console.log(imageArray[i].name+"=="+totalValues[j]);
//imageArray[i].images.push({"url": "https://hexasoft.io"});
//break;
return imageArray[i].images;
}
}
}
//printResult(imageArray);
return [];
}
function printResult(resultArray){
for(var i=0;i<resultArray.length;i++) {
console.log(resultArray[i].name);
for(var j=0;j<resultArray[i].images.length;j++){
console.log(resultArray[i].images[j]);
}
}
}
images = compare(imageArray, totalValues);
if(images.length > 0){
for(var i=0;i<images.length; i++){
images[i].push({"url": "your url"});
}
}
Check out the javascript filter function (Link for the docs).
In your case, you want to do something like this:
function getImagesByAnimalName(animal_name){
var imageArray = imageslide.therapy;
var animalImages = imageArray.filter(animalData => {
return animalData.name === animal_name;
})
return animalImages[0].images;
}
Try it like this. The function will return URLs for each element in totalValues array.
var totalValues = ["cats"];
var slides = imageslide.therapy;
function comp(slides, totalValues ){
let retVal;
for( val of totalValues ) {
for( thisTh of slides ) {
if( thisTh.name == val ){
retVal = thisTh.images;
}
}
}
return retVal;
}
The following will create pics, a flat array of image URLs, if this is what you want:
var pics=[].concat(...imageslide.therapy.map(el=>{
if (totalValues.indexOf(el.name)>-1)
return el.images.map(e=>e.url)}))
console.log(pics);
function compare(imageArray, totalValues) {
for (var a = 0; a < imageArray.length; a++) {
for (var j = 0; j < totalValues.length; j++) {
if (totalValues[j] == imageArray[a].name) {
allValues.push(imageArray[a].images);
for (var i = 0; i < allValues.length; i++) {
for(var j = 0; j < allValues[i].length; j++){
buildSlide(allValues[i][j].url);
}
}
}
}
}
displaySlides(slide_index);
}

How to get an JSON Object based in key using jquery

I'm using jsTree and have tree an structured JSON object.
[{
"id": 1,
"text": "TEXT_ONE",
"children": [
{
"id": 2,
"text": "TEXT_TWO",
"children": [
{
"id": 3,
"text": "TEXT_THREE",
"children": [
]
},
{
"id": 4,
"text": "TEXT_FOUR",
"children": [
]
}
]
},
{
"id": 5,
"text": "TEXT_FIVE",
"children": [
]
}
]
},
{
"id": 6,
"text": "TEXT_SIX",
"children": [ ]
}]
I want to get the the object based on the "id" of the object.
For example if i have a function getIdFromTree(3) it will return me the JSON object as following:
{
"id": 3,
"text": "TEXT_THREE",
"children": []
},
How I do that in Javascript/JQuery?
Try this
function getObjById (tree, id) {
if(tree.id === id) {
return tree;
}
if(tree.children) {
for(var i = 0, l = tree.children.length; i < l; i++) {
var returned = getObjById(tree.children[i], id);
if(returned) {
// so that the loop doesn't keep running even after you find the obj
return returned;
}
}
}
}
Call this as follows
getObjById({children: tree}, 3); // tree is the array object above.
function findById (tree, id) {
var result, i;
if (tree.id && tree.id === id) {
result = tree;
// Revalidate array list
} else if (tree.length) {
for (i = 0; i < tree.length; i++) {
result = findById(tree[i], id);
if (result) {
break;
}
}
// Check childrens
} else if (tree.children) {
result = findById(tree.children, id);
}
return result;
}
Use filter Methode off Array
data.filter(function (obj){ obj.id== 3});
try this.... Es6
function *getObjectById(data, id) {
if (!data) return;
for (let i = 0; i< data.length; i++){
let val = data[i];
if (val.id === id) yield val;
if (val.children) yield *getObjectById(val.children , id);
}
}
now
getObjectById(arrayOfObjects, id).next().value;
try this with most effective and efficient way..
function getObjById (tree, id) {
for(var i= 0;i<tree.length;i++)
{
if(tree[i].id===id)
{
return tree[i];
}
if(tree[i].children)
{
var returned = getObjById(tree[i].children,id);
if(returned!= undefined)
return returned;
}
}
};
link:
https://jsfiddle.net/aa7zyyof/14/

How can i solve "Cannot read property 'length' of undefined at checkWithSeletedModel" in angularjs?

how can i solve this error "Cannot read property 'length' of undefined at checkWithSeletedModel".
when i add object directly in controller its working but when data coming from api i am getting error
TypeError: Cannot read property 'length' of undefined
at checkWithSeletedModel (newbooking.html:404)
at new MyCtrlFun (newbooking.html:391)
at invoke (angular-1.0.1.js:2795)
at Object.instantiate (angular-1.0.1.js:2805)
at angular-1.0.1.js:4620
at angular-1.0.1.js:4201
at forEach (angular-1.0.1.js:117)
at nodeLinkFn (angular-1.0.1.js:4186)
at compositeLinkFn (angular-1.0.1.js:3838)
at compositeLinkFn (angular-1.0.1.js:3841)
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller("MyCtrl", MyCtrlFun);
MyCtrlFun.$inject = ['$scope', '$filter', '$timeout','$http'];
function MyCtrlFun($scope, $filter, $timeout,$http) {
//****** Selected List****
$scope.selectedlist = ["Lumia 735 TS", "Lumia 510"];
$scope.checkbox_model = [];
$scope.checkbox_list = [];
$scope.submitModel = [];
var submodel = [];
var models = {};
var brandname = {};
$scope.finalOutput = {
city:null,
Storename : null,
Offerid : null,
Offer_price : null,
Total_price : null,
Sub_Total_price : null,
Categories : []
}
$scope.finalOutput_withNullFilter = {};
$scope.checkItems = function(){
$scope.checkbox_list = [];
$scope.selectedlist = new Array();
for(var item in $scope.checkbox_model){
if($scope.checkbox_model[item].isChecked)
{
$scope.selectedlist.push($scope.checkbox_model[item].name);
$scope.checkbox_list.push($scope.checkbox_model[item]);
}
}
$scope.checkbox_list.push({offer_id : $scope.selected_offer_id});
//alert(Storename)
/*var m = priceChangeToOffer($scope.selected_offer_id);
if(!isNaN(m)){
$scope.total_price =$scope.total_price-parseInt(m);
}*/
$scope.checkbox_list.push({sub_total : $scope.sub_total});
checkWithSeletedModel();
$scope.finalOutput.city=$scope.phones[0].city;
$scope.finalOutput_withNullFilter = $scope.finalOutput;
if($scope.finalOutput.Storename==null)
{
$scope.finalOutput.Storename = $scope.phones[0].Storename;
}
if($scope.finalOutput.Offerid==null)
{
delete $scope.finalOutput.Offerid;
}
if($scope.finalOutput.Offer_price==null)
{
delete $scope.finalOutput.Offer_price;
}
alert(JSON.stringify($scope.finalOutput));
//****** redefine finalOutput after Submit data to server
$scope.finalOutput = {
city:null,
Storename : null,
Offerid : null,
Offer_price : null,
Total_price : null,
Sub_Total_price : null,
Categories : []
}
}
$scope.selectedbrand = 'Nokia';
$scope.submodel ='Lumia';
$http.get('http://19.168.1.4/shop1/').success(function(data, status, response)
{
//$scope.phones = data
//console.log($scope.phones);
//console i am getting object .here i have added what i have got in console
$scope.phones = [{
"_id": {
"$oid": "56a9c44f40d0275643cfc04e"
},
"default": [],
"Categories": [
{
"models": [
{
"submodel": [
{
"price": "Not available",
"name": "Lumia 735 TS"
},
{
"price": "8100",
"name": "Lumia 510"
},
{
"price": "9900",
"name": "Lumia 830"
}
],
"name": "Lumia"
},
{
"submodel": [
{
"price": "10000",
"name": "Asha 230"
},
{
"price": "11999",
"name": "Asha Asn01"
}
],
"name": "Asha"
}
],
"brandname": "Nokia",
"id": "986745"
},
{
"models": [
{
"submodel": [
{
"price": "5000",
"name": "Trend 840"
},
{
"price": "6999",
"name": "A5"
}
],
"name": "Galaxy"
},
{
"submodel": [
{
"price": "12000",
"name": "Asha 230"
}
],
"name": "Asha"
}
],
"brandname": "Samsung",
"id": "144745"
}
],
"Storename": "Zig Zag Mobiles",
"Shopid":"asdef1234",
"city":"bengaluru",
"__v": 0
}
]
});
//----------------------------Our Shop Offers----------------------------------------
$http.get('http://19.168.1.4/offers/').success(function(data, status, response)
{
//$scope.offers =data;
//console.log($scope.offers);
//console i am getting object .here i have added what i have got in console
$scope.offers = [
{
id: "as23456",
"Storename": "Zig Zag Mobiles",
"Shopid":"asdef1234",
"Offer_message":"1000rs off",
"Categories": [
{
"models": [
{
"submodel": [
{
"price": "1000",
"name": "Lumia 735 TS"
}
],
"name": "Lumia"
}
],
"brandname": "Nokia",
"id": "986745"
}
],
},{
id: "de34575",
"Storename": "Zig Zag Mobiles",
"Shopid":"asdef1234",
"Offer_message":"500rs off",
"Categories": [
{
"models": [
{
"submodel": [
{
"price": "500",
"name": "Lumia 830"
}
],
"name": "Lumia"
}
],
"brandname": "Nokia",
"id": "345645"
}
],
},
{
id: "ert25675",
"Storename": "Zig Zag Mobiles",
"Shopid":"asdef1234",
"Offer_message":"100 Flat",
"Categories": [
{
"models": [
{
"submodel": [
{
"price": "100",
"name": "Asha 230"
}
],
"name": "Asha"
}
],
"brandname": "Samsung",
"id": "345645"
}
],
}
]
});
$scope.offerSelectedList = [];
$scope.total_price = 0, $scope.sub_total=0;
$scope.changeItemStateFun = function(checkbox_value){
if(checkbox_value.isChecked){
if(!isNaN(checkbox_value.price)){
$scope.total_price =$scope.total_price+parseInt(checkbox_value.price);
}
var checked_offer = getOffer([checkbox_value]);
if(checked_offer!=false){
$scope.offerSelectedList.push(checked_offer);
//alert(checked_offer.Categories[0].models[0].submodel[0].name);
}
}else{
if(!isNaN(checkbox_value.price)){
$scope.total_price = $scope.total_price-parseInt(checkbox_value.price);
}
var checked_offer = getOffer([checkbox_value]);
if(checked_offer!=false){
var tempOfferList = [];
for(var i in $scope.offerSelectedList){
if($scope.offerSelectedList[i].id!=checked_offer.id){
tempOfferList.push($scope.offerSelectedList[i]);
}
}
$scope.offerSelectedList = tempOfferList;
}
}
$scope.sub_total = $scope.total_price;
$scope.finalOutput.Total_price = $scope.total_price;
$scope.finalOutput.Sub_Total_price = $scope.sub_total;
}
$scope.selected_offer_id = null;
$scope.submit_offer = {};
$scope.offerSeleted = function(offer){
$scope.selected_offer_id = offer;
var m = priceChangeToOffer($scope.selected_offer_id);
if(!isNaN(m.Offer_price)){
$scope.sub_total =$scope.total_price-parseInt(m.Offer_price);
}
$scope.finalOutput.Storename = m.Storename;
$scope.finalOutput.Offerid = m.Offerid;
$scope.finalOutput.Offer_price = m.Offer_price;
$scope.finalOutput.Total_price = $scope.total_price;
$scope.finalOutput.Sub_Total_price = $scope.sub_total;
}
function getOffer(checkedItem){
for(var i=0; i<checkedItem.length; i++){
for(var j=0; j<$scope.offers.length; j++){
for(var k=0;k<$scope.offers[j].Categories.length; k++){
for(var m=0; m<$scope.offers[j].Categories[k].models.length; m++){
for(var n=0; n<$scope.offers[j].Categories[k].models[m].submodel.length; n++){
if($scope.offers[j].Categories[k].models[m].submodel[n].name==checkedItem[i].name){
return $scope.offers[j];
}
}
}
}
}
}
return false;
}
//-----------------------------------------------------------------------------------
checkWithSeletedModel();
function checkWithSeletedModel(){
$scope.finalOutput.Categories = [];
$scope.submitModel = [];
submodel = [];
models = {};
brandname = {};
$scope.offerSelectedList = [];
$scope.total_price = 0;
$scope.checkbox_model = [];
for(var i=0; i<$scope.phones.length; i++){
for(var j=0; j<$scope.phones[i].Categories.length; j++){
if($scope.phones[i].Categories[j].brandname==$scope.selectedbrand){
brandname = {
id : $scope.phones[i].Categories[j].id,
brandname : $scope.phones[i].Categories[j].brandname,
models : []
};
models = {};
for(var k=0; k<$scope.phones[i].Categories[j].models.length; k++){
if($scope.phones[i].Categories[j].models[k].name==$scope.submodel){
models = {
name : $scope.phones[i].Categories[j].models[k].name,
submodel : []
}
for(var m=0; m<$scope.phones[i].Categories[j].models[k].submodel.length; m++){
var verifyIsCheck = false;
if($scope.selectedlist.length>0){
verifyIsCheck=verifyIsChecked($scope.phones[i].Categories[j].models[k].submodel[m].name);
}
if(verifyIsCheck==true){
models.submodel.push({name : $scope.phones[i].Categories[j].models[k].submodel[m].name, price:($scope.phones[i].Categories[j].models[k].submodel[m].price=='Not available'?null:$scope.phones[i].Categories[j].models[k].submodel[m].price)});
//models.submodel
}
var obj1 = {isChecked :verifyIsCheck, name : $scope.phones[i].Categories[j].models[k].submodel[m].name, price:$scope.phones[i].Categories[j].models[k].submodel[m].price};
//$scope.changeItemStateFun(obj1);
var checkedOffer = getOffer([obj1]);
if(checkedOffer!=false && verifyIsCheck==true){
$scope.offerSelectedList.push(checkedOffer);
}
if(verifyIsCheck==true && !isNaN(obj1.price)){
$scope.total_price = $scope.total_price+parseInt(obj1.price);
}
$scope.checkbox_model.push(obj1);
}
}
}
brandname.models.push(models);
$scope.submitModel.push(brandname);
}
}
}
$scope.finalOutput.Categories.push($scope.submitModel);
}
function verifyIsChecked(submodel_name){
for(var i=0; i<$scope.selectedlist.length; i++){
if($scope.selectedlist[i]==submodel_name){
return true;
}
}
return false;
}
//********** For total sum checked model and change according to offer
function priceChangeToOffer(offer_id){
for(var j=0; j<$scope.offers.length; j++){
if(offer_id!=$scope.offers[j].id)
continue;
for(var k=0;k<$scope.offers[j].Categories.length; k++){
for(var m=0; m<$scope.offers[j].Categories[k].models.length; m++){
for(var n=0; n<$scope.offers[j].Categories[k].models[m].submodel.length; n++){
var offer_obj = {
Storename : $scope.offers[j].Storename,
Offerid : $scope.offers[j].id,
Offer_price : $scope.offers[j].Categories[k].models[m].submodel[0].price
};
return offer_obj;
}
}
}
}
}
$scope.sub_total = $scope.total_price;
$scope.finalOutput.Total_price = $scope.total_price;
$scope.finalOutput.Sub_Total_price = $scope.sub_total;
}
myApp.filter("removespace", function(){
return function(input){
return input.replace(/[^A-Z0-9]+/ig, "_")
}
});
//]]>
//]]>
//]]>
<script type="text/javascript" src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="item" ng-repeat="item in phones">
<div ng-repeat="cat in item.Categories" ng-show="cat.brandname==selectedbrand">
<h2><b>{{ cat.brandname }}</b></h2>
<div ng-repeat="models in cat.models" ng-show="models.name==submodel">
<h3>
<b>{{models.name}}</b>
</h3>
<div ng-repeat="submodels in models.submodel">
<input type="checkbox" ng-model="checkbox_model[$index].isChecked" ng-change="changeItemStateFun(checkbox_model[$index])"/>{{ submodels.name }}
</div><br/><br/>
<b>Sub Total = {{sub_total}}</b><br/>
<select ng-show="offerSelectedList.length>0" ng-model="selected_item" ng-options="offer.id as offer.Offer_message for offer in offerSelectedList" ng-change="offerSeleted(selected_item)">
<option>select offer</option>
</select>
</div>
</div>
<button ng-click="checkItems()">Do</button>
</div>
</div>
how can i solve this pls some one help me out to move forward i have added my code below .
demo
You have kept a for loop like this:
for(var i=0; i<$scope.phones.length; i++)
here you are trying to access the length of $scope.phones variable. But you have defined $scope.phones inside the success callback of your api call. But your api calls are all failing. therefore success callback are never getting called and therefore $scope.phones is always undefined. Thus you are getting error that `cannot read length of undefined'.

Categories