Simple Backbone app not working - javascript

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

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>

Suggestion box app won't display suggestions

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>

How do I swap content

how can I swap content of a div with Vue.js? I think I lack general lifecycle knowledge. Here is what I´ve got so far. After all I need to swap between two Vue-instances and ´d like to use only one lightbox container for them.
Here is what I´ve got so far: http://jsbin.com/qokerah/edit?html,js,output
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script type="x-template" id="foo-template">
<div class="text">{{ fooText }}</div>
<div class="confirm" v-if="fooConfirm">confirmed</div>
</script>
<script type="x-template" id="bar-template">
<div class="heading">{{ barHeading }}</div>
<div class="info">{{ barInfo }}</div>
</script>
<div class="foo">
<div class="btn btn-primary" v-on:click="swapLightboxContent">Open foo template</div>
</div>
<div class="bar">
<div class="btn btn-primary" v-on:click="swapLightboxContent">Open bar template</div>
</div>
<div class="lightbox">
<div class="lightbox-content">Show foo- or bar-template</div>
</div>
</body>
</html>
JS
var foo = new Vue({
el: '.foo',
data: {
fooText: 'text',
fooConfirm: false
},
methods: {
swapLightboxContent: function () {
console.log('Show foo-template');
}
}
});
var bar = new Vue({
el: '.bar',
data: {
barHeading: 'text',
barInfo: 'text'
},
methods: {
swapLightboxContent: function () {
console.log('Show bar-template');
}
}
});
Ok, my main misconception where:
I Used var foo and bar as new Vue() instances without having a parent "intersection" instance
so this is now working:
http://jsbin.com/tiwoco/edit?html,js,output
Still need to figure out if accessing the currentView item through vmFoo and vmBar instances shouldn´t be done in foo and bar components :)

How to get the autocomplete in angular js?

I have a object which contains name and id.I just want to do the autocomplete based on name.I have tried the code as shown below
//Js file
var app=angular.module("myapp",[]);
app.controller("controller",['$scope',function($scope){
$scope.persons=[
{
Name:"Bhavani",
Id:67
},
{
Name:"Mamata",
Id:66
},
{
Name:"Prasanna",
Id:65
},
{
Name:"Ramya",
Id:64
},
{
Name:"Navya",
Id:63
}
];
$scope.complete=function(){
$("#autocomp").autocomplete({
source: $scope.persons.Id
});
};
}]);
//Html file
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<meta charset="UTF-8">
<title>Auto Complete based on name</title>
<script src="angularfiles/angular.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script src="Jsfiles/autocomp.js"></script>
</head>
<body ng-controller="controller">
<div ng-repeat="p in persons">{{p.Name}}
</div>
<div class="ui-widget">
<input type="text" id="autocomp" ng-keyup="complete()">
</div>
</body>
</html>
The above code may have some errors .Its not getting output which i want to have .Can anyone help me out to solve this problem.
Try like this,
HTML:
<div ng-app = "myapp">
<div ng-controller="controller">
<div class="ui-widget">
<input type="text" id="autocomp" auto-complete>
</div>
</div>
</div>
Js:
var app = angular.module("myapp",[]);
app.controller("controller",function($scope){
$scope.availableTags = [
{
Name:"Bhavani",
Id:67
},
{
Name:"Mamata",
Id:66
},
{
Name:"Prasanna",
Id:65
},
{
Name:"Ramya",
Id:64
},
{
Name:"Navya",
Id:63
}
];
}).directive("autoComplete",function(){
return function(scope,element,attrs){
var names =$.map(scope.availableTags,function(value){ return value.Name;
});
element.autocomplete({
source: names
});
};
});
Working jsbin
This is how you should use any jQuery API's in an AngularJS project (i believe). Anytime you are doing DOM Manipulation or jQuery things, it should be placed inside the link: function() {} via directive.
Probably the main problem with your code was that the source: $scope.persons.Id is just a number. The source needs to be an array of Strings (at least as per the documentation). So I seperated all the names from your persons array and placed them in a new array peopleNames
<!doctype html>
<html lang="en" ng-app="myapp">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="vendors/angular.min.js"></script>
</head>
<body ng-controller="controller">
<div ng-repeat="p in persons">{{p.Name}}
</div>
<div class="ui-widget">
<input type="text" id="tags" autocomplete-directive>
</div>
<script>
var app = angular.module("myapp",[]);
app.controller("controller",['$scope',function($scope){
$scope.persons=[
{
Name:"Bhavani",
Id:67
},
{
Name:"Mamata",
Id:66
},
{
Name:"Prasanna",
Id:65
},
{
Name:"Ramya",
Id:64
},
{
Name:"Navya",
Id:63
}
];
// array of only strings autocomplete
$scope.peopleNames = [];
for(var i = 0, j = $scope.persons.length; i < j; i++) {
$scope.peopleNames.push($scope.persons[i].Name);
}
}]);
app.directive('autocompleteDirective', [function($scope) {
return {
link: function(scope, element, attrs) {
element.autocomplete({
source: scope.peopleNames
});
}
};
}]);
</script>
</body>
</html>
Thank For every one for suggesting me answer.I have also done in another way .It may help to others.
//html file
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>Auto Complete based on name</title>
<script src="angularfiles/angular.js"></script>
<script src="angularfiles/angular-animate.js"></script>
<script src="angularfiles/ui-bootstrap-tpls-0.13.4.js"></script>
<script src="angularfiles/bootstrap-theme.css"></script>
<script src="Jsfiles/autocomp.js"></script>
</head>
<body ng-controller="controller">
<div ng-repeat="p in persons">{{p}}</div>
<div class="ui-widget">
<input type="text" ng-model="selected" typeahead="p.Name for p in persons | filter:$viewValue">
</div>
</body>
</html>
//js file
var app = angular.module("myapp",['ui.bootstrap']);
app.controller("controller",['$scope',function($scope){
$scope.persons=[
{
Name:"Bhavani",
Id:67
},
{
Name:"Mamata",
Id:66
},
{
Name:"Prasanna",
Id:65
},
{
Name:"Ramya",
Id:64
},
{
Name:"Navya",
Id:63
}
];
}]);

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>

Categories

Resources