AngularJS: linking a bootstrap collapse div to fields in app.js - javascript

I am an Angularjs beginner and I am trying to make a data driven accordion. I do not wish to use angular-ui. I followed the tutorial for collapse Bootstrap 3 and I came up with this code, but I am stuck with trying to make it data driven.
HTML:
<div class="my-page__my-list-acc" ng-
if="field.fieldAccordions">
<div id="accordion_{{ $index }}">
<div class="panel my-panel-overrides">
<a class="my-panel-heading" data-toggle="collapse" data-parent="#accordion_{{ $index }}" data-target="#collapse1">
{{field.fieldAccordionHeader }} </a>
<div id="collapse1" class="collapse in">
{{ field.fieldAccordionItem }}
</div>
</div>
</div>
</div>
JS:
fieldAccordions: [{
fieldAccordionHeader: 'text',
fieldAccordionItem: 'text',
}],
},{
fieldAccordions: [{
fieldAccordionHeader: 'text',
fieldAccordionItem: 'text',
}],
},{
I am having trouble linking the different parts of the accordion with the html. The program finds fieldAccordions and creates the panel, but it does not get to the fieldAccordionHeader and fieldAccordionItem sections.
Also, the second issue I am having is that if I create different fieldAccordions items, clicking on every one would simply close/open the original fieldAccordions field.
Some help would be appreciated. I am aware that this is probably straight forward, but it would help me understand it better. A plunkr would be ideal!

From what I understand of your question, you are trying to render accordions from an array of objects each representing an individual accordion. If that's the case, I would place the accordion inside and ng-repeat, like this:
var app = angular.module('accordions', []);
app.controller('MainCtrl', function($scope) {
$scope.fieldAccordions = [{
fieldAccordionHeader: 'Header 1',
fieldAccordionItems: [{
desc: 'Item 1 - A'
}, {
desc: 'Item 1 - B'
}]
}, {
fieldAccordionHeader: 'Header 2',
fieldAccordionItems: [{
desc: 'Item 2'
}]
}, {
fieldAccordionHeader: 'Header 3',
fieldAccordionItems: [{
desc: 'Item 3'
}]
}];
});
<!DOCTYPE html>
<html ng-app="accordions">
<head>
<meta charset="utf-8" />
<title>AngularJS Accordions</title>
<link data-require="bootstrap-css#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script data-require="jquery#3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body ng-controller="MainCtrl">
<div class="panel-group" id="accordion">
<div class="panel panel-default" ng-repeat="field in fieldAccordions track by $index">
<div class="panel-heading">
<div class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ $index }}">
{{ field.fieldAccordionHeader }} </a>
</div>
</div>
<div id="collapse{{ $index }}" class="panel-collapse collapse in">
<div class="panel-body">
<div ng-repeat="item in field.fieldAccordionItems track by $index">{{ item.desc }}</div>
</div>
</div>
</div>
</div>
</body>
</html>
Note: I've used the standard Bootstrap 3 classes since you didn't provide your custom styles in the question.

Related

Why is my global variable object (window.[variable]) working locally but not live in the browser?

Junior dev here:
Goal: I would like to define my global variable [array of objects] in one JS file (globalVariables.js) and dynamically access that global variable's key values from different JS (index.js, products.js) and HTML (index.html, products.html, etc.) pages. I will include all of these pages at the bottom.
Essentially, on both index.html and products.html, I am listing my client's products, and the global variable is supposed to fill in all that information dynamically.
According to W3schools section on Global Variables, I should be able to declare the variable like so:
var carName = "Volvo";
and access it like so:
console.log(window.carName)
Unexpected Result: Instead, nothing shows up in the browser and, looking at the console, I read:
jQuery.Deferred exception: Cannot read property '0' of undefined TypeError: Cannot read property '0' of undefined
at HTMLDocument.<anonymous> (https://tiegrrr.com/testing/js/index.js:19:54)
at e (https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js:2:30005)
at t (https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js:2:30307) undefined
Furthermore, if I try defining the global variable like I've seen recommend on some websites...
var window.allProducts = [object, object, object, etc.]
...I get a different error in VS Code:
',' expected.ts(1005)
What am I missing? And why would it work locally but not online, given the directory structure is the same?
==================================================
ALL THE FILES
globalVariables.js
var allProducts = [
{
name: 'TieGrrr Strap',
img: 'tiegrrr-strap.jpg',
desc: "TieGrrr Straps are the safest alternative to stretch and bungee cords. They quickly and securely hold cargo of almost any shape or size. Works great with ladder racks, pipe, lumber, kayaks, rafts, etc.",
popularity:1,
lengths: [3,6,9,12],
colors: ["red","blue","orange","green"],
breakStrengths: ["1,200 lbs"],
cost: 5,
tag:"tiegrrr",
page: "tiegrrr-strap.html"
},
{
name: 'Ratchet Strap',
img: 'Ratchet-S-Hook.jpg',
desc: '',
popularity:2,
lengths: [6,10,12,16],
colors: ["red","blue","orange","green"],
breakStrengths: ['1,500 lb.'],
cost: 8,
tag:"ratchet",
page: "ratchet-strap.html"
},
{
name: 'Heavy Duty Ratchet',
img: 'heavy-duty-strap.jpg',
desc: '',
popularity:3,
lengths: [6,10,12,16],
colors: ["red","blue","orange","green"],
breakStrengths: ['1,500 lb.','3,000 lb.'],
cost: 10,
tag:"heavy",
page: "heavy-duty-ratchet.html"
},
{
name: 'Load Hugger',
img: 'load-hugger.jpg',
desc: '',
popularity:4,
lengths: [6,10,12,16],
colors: ["red","blue","orange","green"],
breakStrengths: ['1,500 lb.'],
cost: 15,
tag:"hugger",
page: "load-hugger.html"
},
{
name: 'Super Duty Ratchet',
img: 'SD Ratchet-F-Hook.jpg',
desc: '',
popularity:0,
lengths: [6,10,12,16],
colors: ["red","blue","orange","green"],
breakStrengths: ['1,500 lb.'],
cost: 12,
tag:"super",
page: "super-duty-ratchet.html"
},
{
name: 'Winch Strap',
img: 'winch-green.jpg',
desc: '',
popularity:0,
lengths: [6,10,12,16],
colors: ["red","blue","orange","green"],
breakStrengths: ['1,500 lb.'],
cost: 9,
tag:"winch",
page: "winch-strap.html"
},
{
name: 'Universal Cam Strap',
img: 'universal-strap1.jpg',
desc: '',
popularity:0,
lengths: [6,10,12,16],
colors: ["red","blue","orange","green"],
breakStrengths: ['1,500 lb.'],
cost: 6,
tag:"uni",
page: "universal-cam-strap.html"
},
{
name: 'Endless Ratchet',
img: 'endless-ratchet-strap.jpg',
desc: '',
popularity:0,
lengths: [6,10,12,16],
colors: ["red","blue","orange","green"],
breakStrengths: ['1,500 lb.'],
cost: 8,
tag:"endless",
page: "endless-ratchet-strap.html"
}
];
indes.js
$(() => {
let $container = $('#item-container')
// TODO: make it so LOOP automatically filters for 1-4
for (i=0;i<4;i++) { // LOOPS through first 4
$newITEM_div = $('<div>') // PARENT div for ITEM + IMG
$newITEM_div.addClass("item")
$newITEM_NAME_div = $('<div>') // div for ITEM NAME
$newITEM_NAME_div.text(window.allProducts[i].name)
$newITEM_NAME_div.addClass("item-name")
$newITEM_IMG = $('<img>')
$newITEM_IMG.css("background-image", `url('../testing/images/${window.allProducts[i].img}')`);
$newITEM_div.append($newITEM_NAME_div)
$newITEM_div.append($newITEM_IMG)
$newITEM_div.attr('onclick',`location.href='./products/${window.allProducts[i].page}'`);
$container.append($newITEM_div)
}
})
console.log(window.allProducts)
products.js
$(() => {
let $container = $('#item-container')
// splits string at every "/" then POPS last array element
var currentPage = $(location).attr('href').split("/").pop();
// TODO: make it so LOOP automatically filters for 1-4 popularity
// on PRODUCTS page, this code loops through ALL PRODUCTS for category imgs
if (currentPage.match("products.html")) {
for (i=0;i<window.allProducts.length;i++) {
$newITEM_div = $('<div>') // PARENT div for ITEM + IMG
$newITEM_div.addClass("product-item")
$newITEM_NAME_div = $('<div>') // div for ITEM NAME
$newITEM_NAME_div.text(window.allProducts[i].name)
$newITEM_NAME_div.addClass("product-item-name")
$newITEM_IMG = $('<img>')
if (currentPage.match("products.html")) {
$newITEM_IMG.css("background-image", `url('../testing/images/${window.allProducts[i].img}')`);
} else {
$newITEM_IMG.css("background-image", `url('../images/${window.allProducts[i].img}')`);
}
$newITEM_div.append($newITEM_NAME_div)
$newITEM_div.append($newITEM_IMG)
$newITEM_div.attr('onclick',`location.href='./products/${window.allProducts[i].page}'`);
$container.append($newITEM_div)
$container.removeAttr('id');
$container.addClass("all-products-container")
}
} else {
for (i=0;i<window.allProducts.length;i++) {
if (currentPage.includes(window.allProducts[i].tag)) {
let currentProduct = window.allProducts[i]
let $productImg = currentProduct.img;
let $productTitle = currentProduct.name;
let $productDesc = currentProduct.desc;
let $productCost = currentProduct.cost;
$("#product-image").attr("src",`../images/`+$productImg);
$('h1').text($productTitle);
$('#description').text($productDesc);
for (i=0;i<currentProduct.lengths.length;i++) { // LOOPS through first 4
$newLength = currentProduct.lengths[i]
$newLength_div = $('<div>')
$newLength_div.text($newLength)
$newLength_div.addClass("length")
$('.lengths').append($newLength_div)
}
for (i=0;i<currentProduct.colors.length;i++) { // LOOPS through first 4
$newColor = currentProduct.colors[i]
$newColor_div = $('<div>')
$newColor_div.addClass("color")
$newColor_div.css("background-color",`${$newColor}`)
$('.colors').append($newColor_div)
}
for (i=0;i<currentProduct.breakStrengths.length;i++) { // LOOPS through first 4
$newBreak = currentProduct.breakStrengths[i];
if (i>0) {
$('#breaks').append(`, `+$newBreak);
} else {
$('#breaks').text($newBreak);
}
}
$('#cost').text(`$`+$productCost+`.00`);
break;
} else {
continue;
}
}
}
})
index.html (head and body, StackOverflow didn't like the full doc for some reason)
<head>
<title>TieGrrr Straps, Inc.</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="TieGrrr Straps, Inc.">
<meta name="description" content="Manufacturers of high quality tie-down systems at competitive prices.">
<meta name="keywords" content="tie downs, tie-downs, tie down straps, ratchet straps, straps, tie downs, tie down systems, tie down manufacturers">
<!-- BOOTSTRAP CSS -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<!-- TieGrrr Strap CSS -->
<link rel="stylesheet" type="text/css" href="css/styles.css">
<!-- add GOOGLE FONTS here-->
<link href="" rel="stylesheet"> <!-- ADD Google Font when ready-->
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- BOOTSTRAP JS -->
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<!-- SLICK carousel -->
<link rel="stylesheet" type="text/css" href="js/slick-1.8.1/slick/slick.css"/>
<!-- Add the new slick-theme.css if you want the default styling -->
<link rel="stylesheet" type="text/css" href="js/slick-1.8.1/slick/slick-theme.css"/>
<!-- JS for INDEX PAGE -->
<script src="js/globalVariables.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div id="top-thin-bar" class="col">800.810.8881 | sales#tiegrrr.com</div>
</div>
</div>
<nav class="navbar sticky-top">
<div id="main-logo" onclick="location.href='https\://tiegrrr.com'"></div>
<div id="nav-info-content">
<div id="main-logo-mobile" onclick="location.href='https\://tiegrrr.com'"></div>
<div id="company-title">TieGrrr Straps, Inc.</div>
<div id="subtitle">Manufacturers of Quality Tie-Down Systems</div>
<div id="buttons">
<div class="active" onclick="location.href='./index.html'">HOME</div>
<div onclick="location.href='./products.html'">PRODUCTS</div>
<div onclick="location.href='./about-us.html'">ABOUT US</div>
<div onclick="location.href='./contact-us.html'">CONTACT</div>
</div>
</div>
<div id="buttons-mobile"> <!-- starts out HIDDEN -->
<div onclick="location.href='./index.html'">HOME</div>
<div onclick="location.href='./products.html'">PRODUCTS</div>
<div onclick="location.href='./about-us.html'">ABOUT US</div>
<div onclick="location.href='./contact-us.html'">CONTACT</div>
</div>
</nav>
<div class="container-fluid">
<div class="row" id="landing-carousel">
<div id="carousel-container" class="col">
<div id="carousel-inner">
<!-- CHANGE which PICS in STYLES.CSS -- look for #on-sale-item- -->
<div id="on-sale-item-1"></div>
<div id="on-sale-item-2"></div>
<div id="on-sale-item-3"></div>
<div id="on-sale-item-1"></div>
<div id="on-sale-item-2"></div>
<div id="on-sale-item-3"></div>
<div id="on-sale-item-1"></div>
<div id="on-sale-item-2"></div>
<div id="on-sale-item-3"></div>
<div id="on-sale-item-1"></div>
<div id="on-sale-item-2"></div>
<div id="on-sale-item-3"></div>
<div id="on-sale-item-1"></div>
<div id="on-sale-item-2"></div>
<div id="on-sale-item-3"></div>
<div id="on-sale-item-1"></div>
<div id="on-sale-item-2"></div>
<div id="on-sale-item-3"></div>
<div id="on-sale-item-1"></div>
<div id="on-sale-item-2"></div>
<div id="on-sale-item-3"></div>
<div id="on-sale-item-1"></div>
<div id="on-sale-item-2"></div>
<div id="on-sale-item-3"></div>
<div id="on-sale-item-1"></div>
<div id="on-sale-item-2"></div>
<div id="on-sale-item-3"></div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col text-center" id="page-content">
<div id="item-container"> <!-- use JAVASCRIPT to LOOP through -->
<!-- index.js fills in with TOP 4 POPULAR ITEMS -->
</div>
View ALL PRODUCTS
<p style="color:white; font-size:x-large; font-style:italic; font-weight:800;">GET A GRIP</p>
<p style="color:white; font-size:1.2em; font-weight:600;">We are a family-owned manufacturing company that aims to provide tie-down systems both superior in quality and price to that of any similar products carried by "big-box" stores.</p>
<p style="color:white; font-size:1em;margin-bottom:3vh;">All of our products meet or exceed both D.O.T. and Web &Sling Assoc. standards for safety. Before we will sell any product, it must pass our field and/or lab test for "normal" abuse. Our products may cost as much as other disposable tie-downs, but they will outlast even the most expensive straps.</p>
<p style="color:red; font-size:large; font-style:italic; font-weight:800;">AMERICAN OWNED</p>
<img id="USAflag" src="./images/USA.jpg">
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col" id="footer">
Copyright © 2007 Tiegrrr Straps, Inc.
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/slick-1.8.1/slick/slick.min.js"></script>
<!-- SLICK carousel inline script -->
<script type="text/javascript">
$('#carousel-inner').slick({
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 8000,
});
</script>
</body>
products.html
<head>
<title>TieGrrr Straps, Inc. - Products</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="TieGrrr Straps, Inc.">
<meta name="description" content="Manufacturers of high quality tie-down systems at competitive prices.">
<meta name="keywords" content="tie downs, tie-downs, tie down straps, ratchet straps, straps, tie downs, tie down systems, tie down manufacturers">
<!-- BOOTSTRAP CSS -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<!-- TieGrrr Strap CSS -->
<link rel="stylesheet" type="text/css" href="css/styles.css">
<!-- add GOOGLE FONTS here-->
<link href="" rel="stylesheet"> <!-- ADD Google Font when ready-->
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- BOOTSTRAP JS -->
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<!-- JS for PRODUCTS PAGE -->
<script src="js/globalVariables.js"></script>
<script src="js/products.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div id="top-thin-bar" class="col">800.810.8881 | sales#tiegrrr.com</div>
</div>
</div>
<nav class="navbar sticky-top">
<div id="main-logo" onclick="location.href='https\://tiegrrr.com'"></div>
<div id="nav-info-content">
<div id="main-logo-mobile" onclick="location.href='https\://tiegrrr.com'"></div>
<div id="company-title">TieGrrr Straps, Inc.</div>
<div id="subtitle">Manufacturers of Quality Tie-Down Systems</div>
<div id="buttons">
<div onclick="location.href='./index.html'">HOME</div>
<div class="active" onclick="location.href='./products.html'">PRODUCTS</div>
<div onclick="location.href='./about-us.html'">ABOUT US</div>
<div onclick="location.href='./contact-us.html'">CONTACT</div>
</div>
</div>
<div id="buttons-mobile"> <!-- starts out HIDDEN -->
<div onclick="location.href='./index.html'">HOME</div>
<div onclick="location.href='./products.html'">PRODUCTS</div>
<div onclick="location.href='./about-us.html'">ABOUT US</div>
<div onclick="location.href='./contact-us.html'">CONTACT</div>
</div>
</nav>
<div class="container-fluid">
<!-- TODO: remove FLEX STYLES from ROW -->
<div class="row">
<div id="carousel-container" class="col">
<div id="item-container">
<!-- PRODUCTS JS fills in -->
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col text-center" id="page-content">
<div style="margin-top: 2.5vh;">
<p style="color:white; font-size:x-large; font-style:italic; font-weight:800;">GET A GRIP</p>
<p style="color:white; font-size:1.2em; font-weight:600;">We are a family-owned manufacturing company that aims to provide tie-down systems both superior in quality and price to that of any similar products carried by "big-box" stores.</p>
<p style="color:white; font-size:1em;margin-bottom:3vh;">All of our products meet or exceed both D.O.T. and Web &Sling Assoc. standards for safety. Before we will sell any product, it must pass our field and/or lab test for "normal" abuse. Our products may cost as much as other disposable tie-downs, but they will outlast even the most expensive straps.</p>
<p style="color:red; font-size:large; font-style:italic; font-weight:800;">AMERICAN OWNED</p>
<img id="USAflag" src="./images/USA.jpg">
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col" id="footer">
Copyright © 2007 Tiegrrr Straps, Inc.
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
</body>
UPDATE: I incorrectly called allProducts an object when I first posted, but it's actually an array of objects, if that matters.
When you're adding something to the window it's usually best to do it explicitly.
So your second solution was probably right but your syntax was wrong, try this:
window.allProducts = {objectValues, objectValues, etc.}
Without the var. You only need to use var when creating the variable, since window already exists it'll error if you try and create it.

ng-repeat multiple row using bootstrap

<div class="row">
<div class="col-xs-12">
<button ng-repeat="item in items track by $index">
{{item}}
</button>
</div>
</div>
I have 3 item and would like to put them like this
1 2 3
4 5 6
so I suppose to have 2 row. But my ng-repeat is the item itself. How do I solve above case?
Try this ,
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{
id: 1,
value: 'column1'
},
{
id: 2,
value: 'column2'
},
{
id: 3,
value: 'column3'
},
{
id: 4,
value: 'column4'
},
{
id: 5,
value: 'column5'
},
{
id: 6,
value: 'column6'
},
{
id: 7,
value: 'column7'
},
{
id: 8,
value: 'column8'
},
];
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css" rel="stylesheet" data-semver="4.0.0-alpha.2" data-require="bootstrap#*" />
<script src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js" data-semver="4.0.0-alpha.2" data-require="bootstrap#*"></script>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="angular.js#1.4.x"></script>
<script src="app.js"></script>
</head>
<body ng-app="plunker" ng-controller="MainCtrl">
<div ng-repeat="item in items">
<div class="col-xs-4">
{{item.value}}
</div>
</div>
</body>
</html>
Here you have a fiddle i made in a few seconds... it should work good without "row" class too.
*{
text-align: center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-xs-12">
<!-- Here goes your ng-repeat -->
<div class="col-xs-4">
1
</div>
<div class="col-xs-4">
2
</div>
<div class="col-xs-4">
3
</div>
<div class="col-xs-4">
4
</div>
<div class="col-xs-4">
5
</div>
<div class="col-xs-4">
6
</div>
<!-- End of ng-repeat -->
</div>
</div>

AngularJS Directive to loop through array

Using AngularJS, I need to create a directive that loops through an array and displays the relevant information:
Here is my code so far but for some reason it is now working.
Kindly help. What is being displayed is the text below as plain text. Obviously the images are not being loaded as well.
info.title
info.developer
info.price | currency
Here are the files used.
appInfo.html - the template to be used by the directive for each element
<img class="icon" ng-src="{{ info.icon }}">
<h2 class="title">{{ info.title }}</h2>
<p class="developer">{{ info.developer }}</p>
<p class="price">{{ info.price | currency }}</p>
appInfo.js - directive
app.directive('appInfo', function() {
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl: 'appInfo.html'
};
});
app.js - module
var app = angular.module('AppMarketApp', []);
controller - repeated elements to test
app.controller('MainController', ['$scope', function($scope) {
$scope.apps =
[
{
icon: 'img/move.jpg',
title: 'MOVE',
developer: 'MOVE, Inc.',
price: 0.99
},
{
icon: 'img/shutterbugg.jpg',
title: 'Shutterbugg',
developer: 'Chico Dusty',
price: 2.99
},
{
icon: 'img/move.jpg',
title: 'MOVE',
developer: 'MOVE, Inc.',
price: 0.99
},
{
icon: 'img/shutterbugg.jpg',
title: 'Shutterbugg',
developer: 'Chico Dusty',
price: 2.99
}
];
}]);
index.html
<!doctype html>
<html>
<head>
<link href="https://s3.amazonaws.com/codecademy-content/projects/bootstrap.min.css" rel="stylesheet" />
<link href="css/main.css" rel="stylesheet" />
<!-- Include the AngularJS library -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</head>
<body ng-app="AppMarketApp">
<div class="header">
<div class="container">
<h1>App Market</h1>
</div>
</div>
<div class="main" ng-controller="MainController">
<div class="container">
<div class="card" ng-repeat="a in apps">
<app-info info="{{a}}"></app-info>
</div>
</div>
</div>
<!-- Modules -->
<script src="app.js"></script>
<!-- Controllers -->
<script src="MainController.js"></script>
<!-- Directives -->
<script src="appInfo.js"></script>
</body>
</html>
Thanks in advance.
You should do
<div class="card" ng-repeat="a in apps">
<app-info info="a"></app-info>
</div>
Attributes that already expect expressions don't need curly braces.

Angular JS drop down to show dynamic content using ng-click and ng-show?

This is my HTML: I am trying to build both the menu and the content shown from the menu in angular js with an object called contests.
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=yes" />
<title>Title Town!</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
</head>
<body>
<div ng-controller="ContestController as contest">
<h2>{{contest.greeting}}</h2>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select a team!
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li ng-repeat="contest in contest.contest" ng-class="{{contest.active}}"><a href ng-click="tab = tab=={{contest.id}} ? a : {{contest.id}}">{{contest.name}}</a></li>
</ul>
</div>
<p ng-repeat="contest in contest.contest" ng-show="{{contest.show}}">{{contest.name}} Contest! </p>
</div>
<br/><br/><br/><br/><br/><p>There should be content displayed above me when a team is clicked. </p>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
</body>
</html>
This is my Javascript. You will see that I have created a controller called contest. I created an object and assigned it to "this.contest = contests". When I inspect my code, everything is loaded properly but there are errors and there isn't too much of a description.. And of course when I click a team name, the paragraph that is supposed to show isn't showing.
Syntax Error: Token 'contest.id' is at column {2} of the expression [{3}] starting at [{4}].
// Code goes here
//main Controller
(function() {
var app = angular.module('app', []);
app.controller('ContestController', function($scope) {
this.greeting = 'Welcome my app!';
this.contest = contests;
$scope.tab = '1';
/* $scope.toggle() = function(id){
$scope.visible = !$scope.visible;
console.log('Test' + id);
};*/
});
var contests = [{
name: 'Seahawks',
active: '{active:tab === 1}',
show: 'tab === 1',
id: '1'
},{
name: 'Colts',
active: '{active:tab===2}',
show: 'tab === 2',
id: '2'
},{
name: 'Badgers',
active: '{active:tab===3}',
show: 'tab === 3',
id: '3'
},{
name: 'Rams',
active: '{active:tab===4}',
show: 'tab === 4',
id: '4'
}];
})();
My plunker
As I commented I've rewritten your code for you: http://plnkr.co/edit/MlOzNqqcrIh7xImysIbU?p=preview
Controller:
(function () {
angular
.module('app', [])
.controller('ContestController', [ContestController]);
function ContestController() {
var self = this;
self.data = {
greeting: 'Welcome my app!',
contests: [
{
name: 'Seahawks',
id: 1
}, {
name: 'Colts',
id: 2
}, {
name: 'Badgers',
id: 3
}, {
name: 'Rams',
id: 4
}
],
currentTab: 0
};
self.data.selectTab = function (tab) {
self.data.currentTab = tab;
}
}
})();
Html:
<div>
<div ng-controller="ContestController as contest">
<h2>{{contest.data.greeting}}</h2>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select a team!
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li ng-repeat="c in contest.data.contests">
<a href ng-click="contest.data.selectTab(c.id)">{{c.name}}</a>
</li>
</ul>
<p ng-show="contest.data.currentTab > 0">{{contest.data.contests[contest.data.currentTab - 1].name}} Contest!</p>
</div>
<p>There should be content displayed above me when a team is clicked. </p>
</div>
</div>
A few things to note:
1) You should strive to put a '.' between all of your controller properties and their data (e.g. use an object property instead of just setting primitives. This is why in my rewrite I assign everything to a data object property.
2) You were using binding expressions where they don't belong. For example, in ng-click and ng-show. Angular was getting confused.
3) You were also trying to use binding like expressions in your controller with the 'active' property that I don't believe will translate the way you thought it would.
4) It is considered best practice to place your css links in the head of your document and your javascript tags just before the body tag. You also had two links pointing to bootstrap's css.
If you have any questions about my example feel free to comment!

Why isn't my jsangular looping through my scope?

So I'm learning directives and controllers in JSAngular. Currently I'm just trying to get the appetizers to loop through on the menu but can't seem to get the output to respond. What am I missing here? Thanks in advance.
MainController.js:
app.controller('MainController', ['$scope', function($scope) {
$scope.today = new Date();
$scope.appetizers = [
{
name: 'Caprese',
description: 'Mozzarella, tomatoes, basil, balsmaic glaze.',
price: 4.95
},
{
name: 'Bruschetta',
description: 'Grilled bread garlic, tomatoes, olive oil.',
price: 4.95
},
{
name: 'Mozzarella Sticks',
description: 'Served with marinara sauce.',
price: 3.95
}
];
$scope.mains = [
{
name: 'Roast Beef Au Jus',
description: 'Delicious Amazing Sauce',
price: 15.99
},
{
name: 'Prime Rib',
description: 'Just like Jacoby/s',
price: 18.95
},
{
name: 'BBQ Ribs',
description: 'Better than Krupa/s',
price: 15.99
}
]
$scope.extras = [
{
name: 'Cole slaw',
},
{
name: 'Creamed Spinach',
},
{
name: 'Boston Baked Beans',
}
]
}]);
<!doctype html>
<html>
<head>
<link href="https://s3.amazonaws.com/codecademy-content/projects/bootstrap.min.css" rel="stylesheet" />
<link href='https://fonts.googleapis.com/css?family=Playfair+Display:400,400italic,700italic|Oswald' rel='stylesheet' type='text/css'>
<link href="css/main.css" rel="stylesheet" />
<script src="js/vendor/angular.min.js"></script>
</head>
<body ng-app='PizzaPlanetApp'>
<div class="header">
<h1><span>Pizza</span><span>Planet</span></h1>
</div>
<div class="main" ng-controller="MainController">
<div class="container">
<h1>Specials for {{ today | date }}</h1>
<h2>Appetizers</h2>
<div class="appetizers row" ng-repeat="appetizer in appetizers">
<div class="item col-md-9">
<h3 class="name"> {{ appetizer.name }} </h3>
<p class="description"> {{ appetizer.description }} </p>
</div>
<div class="price col-md-3">
<p class="price"> {{ appetizers.price | currency }} </p>
</div>
</div>
</div>
</div>
<div class="footer">
<pizza-footer></pizza-footer>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/MainController.js"></script>
</body>
</html>
you need to refer to your PizzaPlanetApp application module first. Add the following line of code before creating the controller.
var app = angular.module("PizzaPlanetApp", []);
This refers to the app you want to create the controller of and contains the list of modules your app depends on.
In your case the list is empty.
jsfiddle

Categories

Resources