Suggestion box app won't display suggestions - javascript

I'm trying to create a suggestion box app in JavaScript using AngularJS 1.X that people can post suggestions on and upvote those suggestions. I'm having trouble getting the suggestions to show up on the page. Help? Here's my code:
index.html:
<!DOCTYPE html>
<html>
<Head>
<title>Suggestion Box</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.2.28/angular-route.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
</Head>
<body ng-app="SuggestionBox" ng-controller="HomeController">
<h1> Suggestion Box </h1>
<form ng-submit="addSuggestion()" style="margin-top: 50px">
<h3> Submit Your Suggestion </h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Great ideas here" ng-model="title"></input>
</div>
<button type="submit" class="btn btn-primary">Suggest</button>
</form>
<div class="main" ng-repeat="post in posts"></div>
<p>
<span class="glyphicon glyphicon-plus-sign" ng-click="upVote(post)"></span> Upvotes: <span id="$scope.posts.upvotes"></span>
</p>
<!-- Modules -->
<script type="text/javascript" src="C:\Users\Olivia\Documents\JS\app.js"></script>
<!-- Controllers -->
<script type="text/javascript" src="C:\Users\Olivia\Documents\JS\controllers\HomeController.js"></script>
<!-- Services -->
<script type="text/javascript" src="C:\Users\Olivia\Documents\JS\Services\Suggestions.js"></script>
</body>
</html>
Controller:
app.controller('HomeController', ['$scope', 'suggestions', function($scope, suggestions) {
$scope.helloWorld = "Hello, AngularJS!",
$scope.posts = Suggestions.posts,
$scope.addSuggestion = function($scope.title) {
if(!$scope.title || $scope.title === "") {
return;
};
$scope.posts.push({
title: $scope.title,
upvotes: 0,
});
$scope.title = '';
}
$scope.upVote = function(post) {
$scope.posts[post].upvotes += 1;
};
}]);
app.js:
var app = angular.module('SuggestionBox', ['ngRoute']);
I haven't added any routing yet so the route is just sitting there
Suggestions.js:
app.factory('Suggestions', [function(){
var demoSuggestions = {
posts: [
{
title: 'Insert suggestion here',
upvotes: 10,
comments: [],
},
{
title: 'See above',
upvotes: 2,
comments: [],
},
]
};
return demoSuggestions;
}]);
Any help would be greatly appreciated. Thanks!

This is a working version. It looks like you're pretty new to AngularJS. Feel free to ask any questions.
"use strict";
var app = angular.module('SuggestionBox', ['ngRoute']);
app.factory('SuggestionsFactory', [function () {
var posts = [
{
title: 'Insert suggestion here',
upvotes: 10,
comments: [],
id: 1
},
{
title: 'See above',
upvotes: 2,
comments: [],
id: 2
}
];
function postFactory(title) {
return {
title: title,
upvotes: 0,
comments: []
}
}
var getPosts = function(){
return angular.copy(posts);
}
var addPost = function (title) {
posts.push(postFactory(title));
}
var removePost = function(id){
// remove from posts by id
}
return {
getPosts: getPosts,
removePost: removePost,
addPost: addPost
}
}]);
app.controller('HomeController', ['$scope', 'SuggestionsFactory', function ($scope, SuggestionsFactory) {
var vm = this;
vm.posts = SuggestionsFactory.getPosts();
vm.title = '';
vm.addSuggestion = function () {
if (vm.title && vm.title !== '') {
SuggestionsFactory.addPost(vm.title);
vm.posts = SuggestionsFactory.getPosts();
vm.title = '';
}
}
vm.upVote = function (post) {
post.upvotes += 1;
};
}]);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.2.28/angular-route.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body ng-app="SuggestionBox" ng-controller="HomeController as vm" class="container">
<div class="row">
<div class="col-sm-12">
<h1> Suggestion Box </h1>
<ng-form style="margin-top: 50px">
<h3> Submit Your Suggestion </h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Great ideas here" ng-model="vm.title" />
</div>
<button type="button" class="btn btn-primary" ng-click="vm.addSuggestion(vm.title)">Suggest</button>
</ng-form>
<div class="main" ng-repeat="post in vm.posts">
<p style="font-weight:bold;">{{post.title}}</p>
<div>
<button ng-click="vm.upVote(post)">upvote</button> Upvotes:
<span id="upvotes">{{post.upvotes}}</span>
</div>
</div>
</div>
</div>
</body>
</html>

Related

Basic JavaScript button interaction

I'm new to JavaScript and Node.js.
I'm trying to get a button in my webpage to call a method in my controller when clicked, but so far I'm getting no response from my controller.
How do I call the .submitEntry() function from my button?
Here's the index.html file:
<!DOCTYPE html>
<meta charset="UTF-8">
<html ng-app='app'>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div ng-controller='GameController' class='container'>
<h1>Palindrome Game</h1>
<h2>Submit a new word!</h2>
<form role='form'>
<div class='form-group'>
<input ng-model="name" class='form-control' placeholder="Your name">
<input ng-model="word" class='form-control' placeholder="Word">
<button ng-click='submitEntry()' class='btn btn-default'>Submit word</button>
</div>
</form>
<h2>Top Scores</h2>
<ul class='list-group'>
<li ng-repeat="score in scores | orderBy:'-points'" class='list-group-item'>
<strong>{{score.name}}</strong> {{score.points}} points
</li>
</ul>
</div>
<script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.js'></script>
<script src='ng/app.js'></script>
</body>
And here's the app.js file:
var app = angular.module('app', []);
const button = document.getElementById('myButton');
button.addEventListener('click', function(e)
{
console.log('button was clicked');
});
app.controller('GameController', function($scope, GameService)
{
console.log("Debug 0");
$scope.submitEntry = function()
{
if (typeof $scope.name === 'undefined' || typeof $scope.word === 'undefined')
{
return;
}
var entry = {
name: $scope.name,
word: $scope.word
};
GameService.submitEntry(entry).success(function(points)
{
$scope.word = undefined;
GameService.getScores().success(function(scores)
{
$scope.scores = scores;
});
});
};
GameService.getScores().success(function(scores)
{
$scope.scores = scores;
});
});
app.service('GameService', function($http)
{
this.getScores = function() {
return $http.get('/api/getScores');
};
this.submitEntry = function(entry) {
return $http.post('/api/submitEntry', entry);
};
});
Thank you very much! Any help that could point me in the right direction will be very appreciated.
Here's a simple button that displays an alert once clicked.
function Channels($scope) {
$scope.test = function() {
alert('button clicked!')
}
}
angular.module('app', [])
.controller('Channels', Channels);
angular.bootstrap(document.body, ['app']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body ng-controller="Channels">
<button ng-click="test()">
test
</button>
</body>

Cant add second ng-controller

I am pretty new in angular/js development so now i stacked with this.
When I add ng-controller="HeaderController" to my HTML code it cant load Angular. If you remove this everything is fine. Why that happened? Thanks for any help and sorry for bad English :)
Code:
(function() {
var app = angular.module ('FunStuff',[]);
app.controller ('TextController',['$scope',function($scope){
$scope.stuff = [];
$scope.add = function(){
$scope.stuff.push ($scope.name);
}
}]);
app.controller ('HeaderController'['$scope',function($scope){
$scope.textClass = '';
$scope.changeClrClss = function(name){
$scope.ClrClss = name;
}
}]);
})();
<!DOCTYPE html>
<html ng-app ="FunStuff">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.32/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>LEARN JS</title>
<meta charset="utf-8">
</head>
<body >
<header ng-class = "ColorClass" ng-controller="HeaderController">
<h1>$~/Path_To_Js/</h1>
<button class="changeColorBtn" ng-click="changeColorClass('white')">
ChangeColorButton
</button>
</header>
<div class="wrapper" >
<article ng-controller = "TextController">
<p>There will be some information</p>
<form ng-submit="add()">
<input ng-model="name"><button>Add</button>
</form>
<ul class="buttons" ng-repeat= "n in stuff track by $index">
<li>{{n}}</li>
</ul>
</article>
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
As your error says, You are missing , after the header controller,
app.controller ('HeaderController',['$scope',function($scope){
$scope.textClass = '';
$scope.changeClrClss = function(name){
$scope.ClrClss = name;
}
}]);
DEMO
var app = angular.module ('FunStuff',[]);
app.controller ('TextController',['$scope',function($scope){
$scope.stuff = [];
$scope.add = function(){
$scope.stuff.push ($scope.name);
}
}]);
app.controller ('HeaderController',['$scope',function($scope){
$scope.textClass = '';
$scope.changeClrClss = function(name){
$scope.ClrClss = name;
}
}]);
<!DOCTYPE html>
<html ng-app ="FunStuff">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.32/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>LEARN JS</title>
<meta charset="utf-8">
</head>
<body >
<header ng-class = "ColorClass" ng-controller="HeaderController">
<h1>$~/Path_To_Js/</h1>
<button class="changeColorBtn" ng-click="changeColorClass('white')">
ChangeColorButton
</button>
</header>
<div class="wrapper" >
<article ng-controller = "TextController">
<p>There will be some information</p>
<form ng-submit="add()">
<input ng-model="name"><button>Add</button>
</form>
<ul class="buttons" ng-repeat= "n in stuff track by $index">
<li>{{n}}</li>
</ul>
</article>
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
(function() {
var app = angular.module ('FunStuff',[]);
app.controller ('TextController',['$scope',function($scope){
$scope.stuff = [];
$scope.add = function(){
$scope.stuff.push ($scope.name);
}
}]);
app.controller ('HeaderController',['$scope',function($scope){
//^^ missing comma here
$scope.textClass = '';
$scope.changeClrClss = function(name){
$scope.ClrClss = name;
}
}]);
})();

AngularJS Directives ng-click

I must make a website. When you press an IMG it adds the template from the directive to another div.
In detail, I have 3 imgs on my website. Hamburger, Cola and Crips. When you press one of them it adds it to the Order List.
HTML code:
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<script src="scripts/angular.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="Stylesheet" type="text/css" href="styles/style.css">
<title>Food Center</title>
<script src="scripts/skrypt.js"></script>
</head>
<body>
<h1 class="ladne"><center>Food Center</center></h1>
<div class="d1" ng-controller="myCtrl" myDir1>
<img src="styles/img/cola.gif"></img>
<img src="styles/img/fryt.gif"></img>
<img src="styles/img/ham.gif"></img>
<br>
<div class="zam" >
Date of order: {{data | date:'yyyy-MM-dd'}}
<br>
Your Order:
</div>
</div>
</body>
</html>
Controller code:
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope) {
$scope.data = new Date();
$scope.hamburger ={
name: 'Hambureger',
}
$scope.frytki = {
name: 'Frytki',
}
$scope.cola = {
name: 'Coca-Cola',
}
});
myApp.directive('dir1', function () {
return {
restrict: 'A',
template: '<br>{{hamburger.nazwa}}'
};
});
I really don't understand these directives. Would be nice if you can help me.

Angularjs ng-repeat, ng-form and validation error

A simplified version of the code:
<!DOCTYPE html>
<html ng-app="main">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.angularjs.org/1.4.3/angular.min.js"></script>
<script>
var app = angular.module("main", []);
app.controller("TestController", function($scope) {
$scope.addresses = [{street: ""}, {street: ""}];
$scope.next = function() {
if ($scope.addressMainForm.addressForm.$valid) {
console.log("valid");
} else {
console.log("invalid");
}
$scope.addresses.push({street: ""});
};
$scope.remove = function(index) {
$scope.addresses.splice(index, 1);
};
});
</script>
</head>
<body>
<div ng-controller="TestController" style="width: 500px;">
<form name="addressMainForm">
<div ng-repeat="address in addresses">
<ng-form name="addressForm">
<input ng-model="address.street" required name="street" type="text" placeholder="street" />
<button ng-if="$index > 0" ng-click="remove($index)">REMOVE</button>
</ng-form>
<br>
</div>
</form>
<br>
<button ng-click="next()">NEXT</button>
</div>
</body>
</html>
which looks in the browser like this:
When I click "REMOVE" and then "NEXT" - javascript error is produced:
Error: $scope.addressMainForm.addressForm is undefined
Why is it undefined if there is clearly still one element remaining in the array? Everything otherwise works fine (console.log output), until all the elements are removed but the last one and "NEXT" is clicked.
When you call $scope.addressMainForm.addressForm.$valid , you are attempting to call check to see if the adressForm element is valid, but your remove function has removed the addresses entry associated with that element. So the form indeed still exists, but that call becomes illegal.
Try this:
<!DOCTYPE html>
<html ng-app="main">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.angularjs.org/1.4.3/angular.min.js"></script>
<script>
var app = angular.module("main", []);
app.controller("TestController", function($scope) {
$scope.addresses = [{street: ""}, {street: ""}];
$scope.next = function() {
if ($scope.addressMainForm.$valid) {
console.log("valid");
} else {
console.log("invalid");
}
$scope.addresses.push({street: ""});
};
$scope.remove = function(index) {
$scope.addresses.splice(index, 1);
};
});
</script>
</head>
<body>
<div ng-controller="TestController" style="width: 500px;">
<form name="addressMainForm">
<div ng-repeat="address in addresses">
<ng-form name="addressForm">
<input ng-model="address.street" required name="street" type="text" placeholder="street" />
<button ng-if="$index > 0" ng-click="remove($index)">REMOVE</button>
</ng-form>
<br>
</div>
</form>
<br>
<button ng-click="next()">NEXT</button>
</div>
</body>
</html>

Simple Backbone app not working

I wrote simple Backbone.js app from manual, but this does't work. Why?
It is a HTML-code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="main.css">
<script src="source/jquery.js"></script>
<script src="source/underscore.js"></script>
<script src="source/backbone.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="menu">
<ul>
<li>Start</li>
<li>Success</li>
<li>Error</li>
</ul>
</div>
<div id="start" class="block">
<div class="userplace">
<label>Enter name<input type="text" id="username"></label>
</div>
<div class="buttonplace">
<input type="button" id="button" value="Check">
</div>
</div>
<div id="error" class="block">
<p>Error - not found!</p>
</div>
<div id="success" class="block">
<p>Win!</p>
</div>
</body>
</html>
And it is a JS-code:
var Controller = Backbone.Router.extend({
routes: {
'': 'start',
'!/': 'start',
'!/error': 'error',
'!/success': 'success'
},
start: function() {
$('.block').hide();
$('#start').show();
},
error: function() {
$('.block').hide();
$('#error').show();
},
success: function() {
$('.block').hide();
$('#success').show();
},
});
var controller = new Controller();
var Start = Backbone.View.extend({
el: '#start',
events: {
'click #button': 'check'
},
check: function() {
console.log('WiN!');
if($("#username").val() == 'test') {
controller.navigate('success', true);
}
else {
controller.navigate('error', true);
}
}
});
var starter = new Start();
Backbone.history.start();
When I select point in menu, all work normal, but when I entered name into field and press button nothing happens. Event not activated. Why?
I think you're calling navigate incorrectly.
Try this:
controller.navigate('!/success', {trigger:true});
Documentation:
http://backbonejs.org/#Router-navigate

Categories

Resources