Using jQuery and AngularJS together? - javascript

I'm new to AngularJS, and this project pushes what I already know about using ng-repeat and controllers.
Goal : To make it so when you select an option from the drop down menu and click the button, the guitars will show up with the assistance of ng-repeat. For now, only the names will show up, but I'm focused on ensuring the app.js file works.
HTML :
<!DOCTYPE html>
<html>
<head>
<title>Angular Project 2</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="myApp">
<header ng-controller="HeaderCtrl">
<h1 id="title">{{appDetails.title}}</h1>
<h3 id="tagline">{{appDetails.tagline}}</h3>
</header>
<select id="dropdown">
<option value="Yamaha">Yamaha</option>
<option value="Gibson">Gibson</option>
<option value="Jackson">Jackson</option>
<option value="ESP">ESP</option>
</select>
<br>
<input type="submit" id="searchGuitars" value="Search!">
<section id="bookSection" ng-controller="GuitarCtrl">
<div ng-repeat="guitar in guitars">
{{guitar.title}}
</div>
</section>
</body>
</html>
JS :
var app = angular.module("myApp", []);
app.controller("HeaderCtrl", function ($scope) {
$scope.appDetails = {
title: "JamLog",
tagline: "Take a look at our Fancy Instruments in Stock!"
};
})
app.controller("GuitarCtrl", function ($scope) {
$('#searchGuitars').click(function() {
if ($('#dropdown').val() == "Yamaha") {
$scope.guitars = [
{
title: "Yamaha Revstar 420",
instrument: "Electric Guitar",
color: "Red",
price: "$499.99",
details: "Yes",
imageURL: "YamahaRS420.jpg"
},
{
title: "Yamaha Pacifica Series PAC012",
instrument: "Electric Guitar"
color: "Blue",
price: "$",
details: "Yes",
imageURL: "YamahaPacificaSeriesPAC012.jpg"
}
];
}
else if ($('#dropdown').val() == "Gibson") {
$scope.guitars = [
{
title: "Gibson Les Paul Custom",
instrument: "Electric Guitar",
color: "Blue",
price: "$",
details: "Yes",
imageURL: "GibsonLesCustomBlue.jpg"
},
{
title: "Thunderbird",
instrument: "Bass",
color: "Black",
price: "$",
details: "Used by SOAD Bassist",
imageURL: "GibsonThunderbirdIV.jpg"
}
];
}
})
})
I'm hoping it's not a small error I missed, but the overall layout of this program seems as if it would work, and am unsure as to why not.

Please try to declare JQuery CDN before Angular
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js

If you already use the angularjs, do not mix it up with JQuery.
Maybe this solution below could help you.
"use strict";
angular
.module('app')
.controller("HeaderCtrl", function ($scope) {
$scope.appDetails = {
title: "JamLog",
tagline: "Take a look at our Fancy Instruments in Stock!"
};
})
.controller("GuitarCtrl", function ($scope) {
$scope.searchGuitars = function(guitar) {
if (guitar == "Yamaha") {
$scope.guitars = [
{
title: "Yamaha Revstar 420",
instrument: "Electric Guitar",
color: "Red",
price: "$499.99",
details: "Yes",
imageURL: "YamahaRS420.jpg"
},
{
title: "Yamaha Pacifica Series PAC012",
instrument: "Electric Guitar",
color: "Blue",
price: "$",
details: "Yes",
imageURL: "YamahaPacificaSeriesPAC012.jpg"
}
];
}
else if (guitar == "Gibson") {
$scope.guitars = [
{
title: "Gibson Les Paul Custom",
instrument: "Electric Guitar",
color: "Blue",
price: "$",
details: "Yes",
imageURL: "GibsonLesCustomBlue.jpg"
},
{
title: "Thunderbird",
instrument: "Bass",
color: "Black",
price: "$",
details: "Used by SOAD Bassist",
imageURL: "GibsonThunderbirdIV.jpg"
}
];
}
console.log($scope.guitars);
}
});
<!DOCTYPE html>
<html>
<head>
<title>Angular Project 2</title>
<meta charset="utf-8">
<!--<link rel="stylesheet" href="style.css">-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<!--<script src="app.js"></script>-->
</head>
<body ng-app="app">
<header ng-controller="HeaderCtrl">
<h1 id="title">{{appDetails.title}}</h1>
<h3 id="tagline">{{appDetails.tagline}}</h3>
</header>
<select id="dropdown" ng-model="dropdownSelect">
<option value="Yamaha">Yamaha</option>
<option value="Gibson">Gibson</option>
<option value="Jackson">Jackson</option>
<option value="ESP">ESP</option>
</select>
<br>
<div ng-controller="GuitarCtrl">
<input type="button" ng-click="searchGuitars(dropdownSelect)" id="searchGuitars" value="Search!">
<section id="bookSection">
<div ng-repeat="guitar in guitars">
{{guitar.title}}
</div>
</section>
</div>
</body>
</html>

Related

VueJS Template not rendering

I am struggling to get one of my template components to render. I am sure the mistake is simple but I am having trouble finding a solution since I am new to VueJS. My header shows up just fine but my Questions component is invisible.
Any help would be appreciated. Thank you.
Here is the code.
index.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>Lionsfield Placement Quiz</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
<link rel="stylesheet" type="text/css" href="/styles.css">
<script defer src="https://use.fontawesome.com/releases/v5.1.0/js/all.js"></script>
<style>
.is-loading {
background: cyan;
}
</style>
</head>
<body>
<div class="space-top container shadow" align="center">
<div id="app">
</div>
</div>
<script src="/index.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"
integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"
integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</body>
</html>
App.vue
<template>
<div id="app">
<HeaderSection />
<QuestionSection />
</div>
</template>
<script>
import HeaderSection from "./components/HeaderSection";
import QuestionSection from "./components/QuestionSection";
export default {
name: "App",
components: {
HeaderSection,
QuestionSection
}
};
</script>
HeaderSection.vue
<template>
<div>
<img class="logo" src="/img/lion.png" alt />
<h1 id="heading-top">Lionsfield English Quick Placement Quiz</h1>
</div>
</template>
<script>
export default {
name: "HeaderSection"
};
</script>
QuestionSection.vue
<template>
<div>
<div v-for="(question, index) in quiz.questions" v-bind:key="question.id">
<div v-show="index === questionIndex">
<h2 id="question-text">{{ question.text }}</h2>
<div class="row">
<ul>
<li
class="col-sm-12 col-md-12 col-lg-6"
v-for="(response, index2) in question.responses"
v-bind:key="response.text"
>
<div class="btn-group btn-group-toggle">
<label class="btn btn-red btn-block quesion-b">
<input
type="radio"
v-bind:value="response.correct"
v-bind:name="index"
v-bind:id="index2"
v-bind:class="{ active: isActive }"
v-model="userResponses[index]"
#click="select();next();roundProg()"
checked
/>
{{response.text}}
</label>
</div>
</li>
</ul>
<div class="progress">
<div
class="progress-bar bg-red"
role="progressbar"
:style="{ width: myWidth + '%' }"
aria-valuenow="45"
aria-valuemin="0"
aria-valuemax="100"
>{{prog}}%</div>
</div>
</div>
<button
type="button"
class="btn btn-primary mb-5 btn-sm"
v-if="questionIndex > 0"
v-on:click="prev();roundProg()"
>Previous Question</button>
<!-- <button type="button" class="btn btn-primary btn-sm" v-on:click="next();roundProg()">
Next Question
</button>-->
</div>
</div>
<div v-show="questionIndex === quiz.questions.length">
<h2>You did Amazing job {{quiz.user}}!!!</h2>
<p>
<!--Total score: {{ score() }} / {{ quiz.questions.length }}-->
Total score: {{ score() }}%
</p>
</div>
</div>
</template >
<script>
let quiz = {
user: "English Learner",
questions: [
{
id: 0,
text: "What _______ your job?",
responses: [
{ text: "are" },
{ text: "is", correct: true },
{ text: "be" },
{ text: "have" }
]
},
{
id: 1,
text: "Lynn _______ at home at the moment.",
responses: [
{ text: "works" },
{ text: "is working", correct: true },
{ text: "work" },
{ text: "are working" }
]
},
{
id: 2,
text: "We have ______ information about that.",
responses: [
{ text: "a lot of", correct: true },
{ text: "an" },
{ text: "any" },
{ text: "many" }
]
}
]
};
export default {
data: function() {
return {
quiz: quiz,
questionIndex: 0,
userResponses: Array(quiz.questions.length).fill(false),
isActive: false,
myWidth: 0,
prog: 0
};
},
methods: {
roundProg: function() {
this.prog = Math.round(this.myWidth);
},
select: function() {
isActive = true;
console.log(this);
},
next: function() {
this.questionIndex++;
this.myWidth = (this.questionIndex / quiz.questions.length) * 100;
},
prev: function() {
this.questionIndex--;
this.myWidth = (this.questionIndex / quiz.questions.length) * 100;
},
score: function() {
let n =
(this.userResponses.filter(function(val) {
return val;
}).length /
quiz.questions.length) *
100;
function truncate(num, places) {
return Math.trunc(num * Math.pow(10, places)) / Math.pow(10, places);
}
return truncate(n, 2);
}
}
};
</script>
index.js
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
My HeaderSection and QuestionSection are in the components folder located in the src folder
Syntax error. It is very usefull at first to open Developer Tools, and it saves more time if you use developement enviroment with lint checking like Visual Studio Code.
Must be:
let quiz = {
user: "English Learner",
questions: [
{
id: 0,
text: "What _______ your job?",
responses: [
{ text: "are" },
{ text: "is", correct: true },
{ text: "be" },
{ text: "have" }
]
},
{
id: 1,
text: "Lynn _______ at home at the moment.",
responses: [
{ text: "works" },
{ text: "is working", correct: true },
{ text: "work" },
{ text: "are working" }
]
},
{
id: 2,
text: "We have ______ information about that.",
responses: [
{ text: "a lot of", correct: true },
{ text: "an" },
{ text: "any" },
{ text: "many" }
]
}
]
};

AngularJS ng-repeat does not render

I am now practicing AngularJS.
My Problem is :ng-repeat does not repeat my array.
index.html:
<!DOCTYPE html>
<html ng-app="store">
<head>
<link rel="stylesheet" type="text/css" href="node_modules/bootstrap/dist/css/bootstrap.min.css" />
</head>
<body ng-controller="StoreController as store">
<div ng-repeat="product in store.products">
<h1> {{product.name}}</h1>
<h2> ${{product.price}}</h2>
<p> {{product.description}} </p>
<button ng-show="product.canPurchase">Add to cart</button>
</div>
<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js:
(function(){
var app = angular.module('store', []);
var gems = [{name: 'Dodecahedron',
price: 2.95,
description: 'Hidden mass',
canPurchase : true,
soldOut : true},
{name: 'Pentagonal gem',
price: 5.95,
description: 'Vacuum mass',
canPurchase : false,
soldOut : false}
}];
app.controller('StoreController', function(){
this.products = gems;
});
})();
Can anybody tell me where the fault is?
You provided extra }
here
{name: 'Pentagonal gem',
price: 5.95,
description: 'Vacuum mass',
canPurchase : false,
soldOut : false} <- here
}];
Remove that
{
name: 'Pentagonal gem',
price: 5.95,
description: 'Vacuum mass',
canPurchase: false,
soldOut: false
}];
DEMO

Semantic-ui search local static variable, why no results?

Cannot for the life of me figure out how to get the semantic-ui search component to work correctly...
Many, many examples (semantic-ui.com, jsfiddle, etc) make it look simple. Following this simple pattern does not produce the same results as with said examples.
I've tried inserting debugger statements and using the console to check that the variables exist when needed, tried linking the search component js and css files alongside the rest of the semantic js and css, also tried setting the source, and so on, on the search method manually – no luck all around.
Here's my search input:
<div class="ui search">
<div class="ui icon input" style="width: 100%;">
<input class="prompt" type="text" placeholder="Search...">
<i class="search icon"></i>
</div>
<div class="results"></div>
</div>
Here's the js on same page below:
<script type="text/javascript">
window.onload = function() {
// Setup search
var content = [
{ title: 'Andorra' },
{ title: 'United Arab Emirates' },
{ title: 'Afghanistan' },
{ title: 'Antigua' },
{ title: 'Anguilla' },
{ title: 'Albania' },
{ title: 'Armenia' }
];
$('.ui.search')
.search({
type: 'standard',
source: content,
searchFields : ['title'],
});
}
</script>
Please help. Thank you.
UPDATE 1:
I get some kind of resemblance of functionality when I change the jQuery selector to the .ui.input like so
$('.ui.input')
.search({
type: 'standard',
source: content,
searchFields : ['title'],
});
But it looks like this...
UPDATE 2:
If I keep the jQuery selector $('.ui.search'), the DOM is updated with the search results, but still is not presented correctly...
Following code working fine for me:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="js/search.css">
<script src="js/search.js"></script>
<script type="text/javascript">
window.onload = function() {
// Setup search
var content = [
{ title: 'Andorra' },
{ title: 'United Arab Emirates' },
{ title: 'Afghanistan' },
{ title: 'Antigua' },
{ title: 'Anguilla' },
{ title: 'Albania' },
{ title: 'Armenia' }
];
$('.ui.search')
.search({
type: 'standard',
source: content,
searchFields : ['title'],
});
}
</script>
</head>
<head>
<title> Test </title>
</head>
<body>
<div class="ui search">
<div class="ui icon input" style="width: 100%;">
<input class="prompt" type="text" placeholder="Search...">
<i class="search icon"></i>
</div>
<div class="results"></div>
</div>
</body>
</html>
Turns out to be a css conflict. I had added the following at some point to handle displaying some tabular data with many fields. Simply removing it fixed everything.
*, body {
overflow-x: scroll;
}
TAKE AWAY: semantic-ui likes to be the only css in town!

Angular JS image array coding trouble

I can't get the images to display, it's supposed to display a thumbnail and full image for each "gem" the angular tutorial isn't detailed enough..
heres my html code:
<!DOCTYPE html>
<html ng-app="store">
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css"/>
</head>
<body ng-controller="StoreController as store">
<ul class="list-group">
<li class="list-group-item" ng-repeat="product in store.products">
<h3>
{{product.name}}
<em class="pull-right">{{product.price | currency}}</em>
<img ng-src="{{product.images[0].full}}"/>
</h3>
</li>
</ul>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
JS CODE:
(function(){
var app = angular.module('store', []);
app.controller('StoreController', function(){
this.products = gems;
});
var gems = [
{
name: "dodecahedron",
price: 2.95,
description: ". . .",
images: [
{
full: 'gemfull.gif',
thumb: 'gemthumb.gif'
},
{
full: 'gemfull.gif',
thumb: 'gemthumb.gif'
},
],
name: "Pentagonal Gem",
price: 5.95,
description: ". . .",
images: [
{
full: 'gemfull.gif',
thumb: 'gemthumb.gif'
full: 'gemfull.gif',
thumb: 'gemthumb.gif'
},
],
]
})();
How can i get this to work?
It's supposed to be like a shop, but i can't seem to get the JS (or html) to work proper instead i just get "{{product.name}} {{product.price | currency}}" in the browser when i run the document
Your var gems = [ variable is not proper formated.
I have fix var gems variable and your code is working fine. Closing braces [, { are not at proper places.
Check below snippet without images:
(function(){
var app = angular.module('store', []);
var gems = [{
name: "dodecahedron",
price: 2.95,
description: ". . .",
images: [
{
full: 'gemfull.gif',
thumb: 'gemthumb.gif'
},
{
full: 'gemfull.gif',
thumb: 'gemthumb.gif'
},
]},{
name: "Pentagonal Gem",
price: 5.95,
description: ". . .",
images: [
{
full: 'gemfull.gif',
thumb: 'gemthumb.gif'
},{
full: 'gemfull.gif',
thumb: 'gemthumb.gif'
},
],
}
];
app.controller('StoreController', function(){
this.products = gems;
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="store">
<head>
</head>
<body ng-controller="StoreController as store">
<ul class="list-group">
<li class="list-group-item" ng-repeat="product in store.products">
<h3>
{{product.name}}
<em class="pull-right">{{product.price | currency}}</em>
<img ng-src="{{product.images[0].full}}"/>
</h3>
</li>
</ul>
</body>
</html>

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