I've recently been teaching myself angularjs as well as node.js , from what I've learned I wrote this piece of code , but it isn't functioning , I tried logging something in the controller and it didnt log it so maybe that's a hint on what's wrong index.html code: (sorry in advance if my code is messy or anything )
<!Doctype html>
<html ng-app="Test">
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="angular-route.js"></script>
<script type="text/javascript">
var app= angular.module('Test' , ['ngRoute']);
app.controller('TestController' , function($scope , $http ){
$scope.submitBlog = function(){
$http.post('/blogs' , {blog : $scope.blog}).then(function(){
alert("success");
});
};
});
</script>
</head>
<body ng-app>
<h2>Blog It!</h2>
<br><br>
<div class="test" >
<input type="text" , placeholder="Username">
<br><br>
<input type="password" , placeholder="Password">
<br><br>
<button type="button" > Log In</button>
<br><br>
Not a member ? Sign Up!
</div>
<div class="blogfeed">
<h5>Feed :</h5>
<input ng-model="blog" placeholder="Your thoughts?" >
<button type="button" , ng-click="submitBlog()" , class="btn">Submit</button>
</div>
</body>
</html>
Server code :
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var express = require('express');
var bodyParser = require('body-parser');
var bcrypt = require('bcryptjs');
var app = express();
var db = null;
MongoClient.connect("mongodb://localhost:27017/test" , function(err,dbconn){
if(!err){
console.log("We are connected");
db= dbconn;
}
});
app.use(express.static('public'));
app.use(bodyParser.json());
app.post('/blogs' , function(res,req,next){
db.collection('blogs' , function(err , blogsCollection){
var newBlog= {
text: req.body.blog
};
blogsCollection.insert(newBlog , {w:1} , function(err){
return res.send();
});
});
});
app.listen(3000, function(){
console.log('Example app listening on port 3000');
});
You are creating a controller that is never used.
you have to bind your controller to a dom element with the ng-controller directive
you could append it to the body tag like so
<body ng-app ng-controller="TestController" >
Check this. You've created a ng-app i.e Testand a controller TestController. But you've never used it. If you want to use the controller for the whole body i.e one controller for the whole application then use ng-controller="TestController" on the body tag. Similarly do it for other elements if you want the scope of the controller limited to the children of a particular element.
<!Doctype html>
<html ng-app="Test">
<head>
<title>Test</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.5/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('Test', []);
app.controller('TestController', function($scope, $http) {
console.log('In the controller');
$scope.submitBlog = function() {
$http.post('/blogs', {
blog: $scope.blog
}).then(function() {
alert("success");
});
};
});
</script>
</head>
<body ng-controller="TestController">
<h2>Blog It!</h2>
<br>
<br>
<div class="test">
<input type="text" , placeholder="Username">
<br>
<br>
<input type="password" , placeholder="Password">
<br>
<br>
<button type="button">Log In</button>
<br>
<br>
Not a member ? Sign Up!
</div>
<div class="blogfeed">
<h5>Feed :</h5>
<input ng-model="blog" placeholder="Your thoughts?">
<button type="button" , ng-click="submitBlog()" , class="btn">Submit</button>
</div>
</body>
</html>
Related
I build a simple express js calculator and I want the calculate to show the answer on the same page with the text boxes where I enter the numbers, now after I click calc I move to a blank page with the answer, instead I want a section under the calc button which show "Answer: XXX"
app.js
const express= require("express");
const bodyParser=require("body-parser");
const app= express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public"))
app.get("/",function(req,res){
res.render('home');
});
app.get("/add",function(req,res){
res.render('add');
});
app.post("/add",function(req,res){
var num1=Number(req.body.n1);
var num2=Number(req.body.n2);
var result=num1+num2;
res.send("Answer: "+result);
});
add.ejs
<!DOCTYPE html>
<html dir="rtl">
<head>
<title>calc add</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<form action="/add" method ="post">
<input type="text" class="input" name="n1" placeholder="enter x1"><br>
<br>
<input type="text" class="input" name="n2" placeholder="enter x2"><br>
<br>
<button type="submit" class="submit" name="Submit">calc!</button>
</form>
<br>
<a class="back" href="/">home</a>
</body>
</html>
You can use fetch to make the POST request and get the answer.
<p id="result"></p>
<script>
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
fetch(this.action, {method: this.method, body: new FormData(this)})
.then(res => res.text()).then(ans => {
document.getElementById("result").textContent = ans;
});
});
</script>
So I've been trying to get the data from my form and input it into my database for ages and it just isn't working. There are no errors and nothing is logging.
This is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta charset="UTF-8">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Signup for NGOs</title>
</head>
<body>
<form class="mt-4 mr-4 ml-4" id="form" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name of NGO">
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="Address">
</div>
<div class="form-group">
<label for="phone">Contact Information</label>
<input type="number" class="form-control" id="phone" placeholder="Contact Number">
</div>
<div class="form-group">
<label for="requirements">Requirements (Seperate by Commas)</label>
<input type="text" class="form-control" id="requirements" placeholder="Requirements">
</div>
<button type="submit" class="btn btn-primary" id="submitButton">Submit</button>
</form>
<!-- Optional JavaScript -->
<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.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="signup.js"></script>
</body>
</html>
And this is my Node.js code:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, 'public')));
// I've replaced my original username and password with placeholders
var uri = "mongodb+srv://username:password#helpbook-rlpsi.gcp.mongodb.net/test?retryWrites=true";
var dbConn = MongoClient.connect(uri, { useNewUrlParser: true });
app.post('/signup', function (req, res) {
dbConn.then(function(db) {
delete req.body._id; // for safety reasons
dbConn.db("NGOs").collections("partners").insertOne(req.body);
console.log('test');
});
});
I don't know what's going wrong. My data isn't being uploaded to the database and for some reason none of the console.log() statements are being executed.
The promise probably resolves before the signup handler is called.
Try the following:
var dbConn = MongoClient.connect(uri, { useNewUrlParser: true });
dbConn.then(function(client) {
app.post('/signup', function (req, res) {
delete req.body._id; // for safety reasons
client.db("NGOs").collections("partners").insertOne(req.body);
console.log('test');
});
})
.catch(function(err){
console.log(err)
});
Looking at your question specifically, you are not using any action in your form.
<form class="mt-4 mr-4 ml-4" id="form" method="post" action="/signup">
...
</form>
So it is not getting posted to your route. (That's why I specifically asked if console logging before the dbconn is working or not)
I'm learning Angular.js. I want to make a form where the user can see the output has they fill it out.
Here's test.html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0-rc.2/angular.js"></script>
<script src="test.js"></script>
</head>
<body ng-app="charter">
<div id="layout-wrapper" ng-controller="graphicLanguageCTRL">
<form id="graphic-language" ng-controller="graphicLanguageCTRL" novalidate>
<h3>Language</h3>
<input type="text" name="headline" placeholder="Headline" ng-model="graphic.hed"> <br>
</form>
</div>
<h1 class="graphic-title" ng-bind="graphic.hed"></h1>
</body>
Here's test.js:
var app= angular.module("charter",[]);
app.controller("graphicLanguageCTRL",function($scope){
$scope.master= {
hed: ''
};
});
I want the stuff typed into the input tag to be visible in the h1 tag. But when I type into the input tag, nothing appears in the h1 tag.
How do I fix this?
There are some errors in your code:
You are using ng-bind outside of controller
You are initializing graphicLanguageCTRL twice
In your script you are setting the wrong variable name
Below is the fixed code:
html
<body ng-app="charter">
<div id="layout-wrapper" ng-controller="graphicLanguageCTRL">
<form id="graphic-language" novalidate>
<h3>Language</h3>
<input type="text" name="headline" placeholder="Headline" ng-model="graphic.hed"> <br>
</form>
<h1 class="graphic-title" ng-bind="graphic.hed"></h1>
</div>
</body>
JS
var app = angular.module("charter",[]);
app.controller("graphicLanguageCTRL", function($scope){
$scope.graphic = {
hed : ''
};
});
var app = angular.module("charter",[]);
app.controller("graphicLanguageCTRL",function($scope){
$scope.graphic = {
hed: ''
};
});
or
var app = angular.module("charter",[]);
app.controller("graphicLanguageCTRL",function($scope){
$scope.graphic = {};
$scope.graphic.head = ''
});
2 things need to be taken care of:
Do not nest and use the same ng-controller
Move the h1 inside
the ng-controller block
Fixed version:
var app = angular.module('charter', []);
app.controller("graphicLanguageCTRL", function($scope) {
$scope.graphic = {
hed: ''
};
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0-rc.2/angular.js"></script>
<meta charset="utf-8">
<title>test</title>
</head>
<body ng-app='charter'>
<div id="layout-wrapper" ng-controller="graphicLanguageCTRL">
<form id="graphic-language" novalidate>
<h3>Language</h3>
<input type="text" name="headline" placeholder="Headline" ng-model="graphic.hed">
<br>
</form>
<h1 class="graphic-title" ng-bind="graphic.hed"></h1>
</div>
</body>
</html>
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>
Here i have two ng-apps and there controllers.Here is i want to access controller value in other controller with there different ng-apps .But i am getting error.please help me out.
Thank you.
Html:-
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="service.js"></script>
</head>
<body>
<div id="myDiv1">
<div ng-app="mainApp" ng-controller="CalcController">
<p>Enter a number: <input type="number" ng-model="number" />
<button ng-click="multiply()">X<sup>2</sup></button>
<p>Result 1: {{result}}</p>
</div>
</div>
<div ng-app="myDiv2">
<div ng-controller="MyController2">
<p>Enter a number: <input type="number" ng-model="numberSecond" />
<button ng-click="multiplyValue()">X<sup>2</sup></button>
<p>Result 2: {{result2}}</p>
</div>
</div>
</body>
</html>
Controller.js:
angular.module('myReuseableMod',[]).factory('$myReuseableSrvc',function() {
var factory = {};
factory.multiply = function(a) {
return a * a
}
return factory;
});
var mainApp = angular.module("mainApp", ["myReuseableMod"]);
mainApp.controller('CalcController', ['$scope', '$myReuseableSrvc',function($scope, $myReuseableSrvc) {
$scope.multiply = function() {
$scope.result = $myReuseableSrvc.multiply($scope.number);
}
$scope.aB=function()
{
alert("hiii");
}
}]);
var mainApp2 = angular.module("mainApp2", ['mainApp']);
mainApp2.controller('MyController2',['CalcController' '$scope','$myReuseableSrvc',function(CalcController,$scope, $myReuseableSrvc) {
console.log('init B');
$scope.multiplyValue = function() {
$scope.result2 = $myReuseableSrvc.multiply($scope.numberSecond);
CalcController.aB(); //here i want to acess controller 'CalcController' method.
}
}]);
Here is my plunker:
http://plnkr.co/edit/6QyDuV330YlgXy16S2YX?p=preview
You have to manually bootstrap them.
See :
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application http://docs.angularjs.org/api/ng.directive:ngApp