Render html files with EJS with angular in it - javascript

I have a node + angular project. I want to render a html page and init it with some values. I wan thoses values to be linked to the Angular scope.
So i have an input, I linked it with ng-model but this erase the EJS initialisation.
server.js:
var express = require('express');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/front/views');
app.set('view engine', 'html');
app.use('/front',express.static(__dirname + '/front'));
app.get('/signup',function(req,res){
res.render('view',{
user:{
email:"user mail",
}
})
});
var port = 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});
view.html:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="/front/controllers/app.js"></script>
<html ng-app="onboardingApp">
<form id="msform" novalidate ng-controller="onboardingController">
<input required type="text" name="email" ng-model="signup.user.email">
<label for="email">Email</label>
<input type="button" name="next" ng-click="displaySignup()" value="NEXT"/>
</form>
</html>
app.js:
var onboardingApp = angular.module('onboardingApp', []);
onboardingApp.controller('onboardingController',function OnboardingController($scope) {
$scope.signup = {
user:{
email:""
}
}
$scope.displaySignup = function(){
console.log($scope.signup)
}
});
So I am trying to set the value of: input required type="text" name="email" ng-model="signup.user.email"
with ejs and then that this value to be linked with the angular model signup.user.email.
Can someone help me with that?

you can add this piece of js at the end of your view.html
<script type="text/javascript">
angular.module('onboardingApp')
.value('userEmail', <%- JSON.stringify(user.email) %>);
</script>
and then inject the component wherever you need it like so:
onboardingApp.controller('onboardingController',
function OnboardingController($scope, userEmail) {
$scope.signup = {
user:{
email: userEmail
}
}
$scope.displaySignup = function(){
console.log($scope.signup)
}
});

Related

unidentified object post from angularjs controller in expressjs [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
i have project of login page for admin redirect to dashboard. it use expressjs as a server side and angularjs as a client side.
this client side login page use angularjs
//this is the angular controller that use for get the data from login form
(function () {
'usestrict';
"the initialize angular module"
angular.module("myAdmin",[]).controller('loginCtrl', function($scope, $http){
$scope.login = function() {
var userEmail = $scope.user.email;
var userPassword = $scope.user.password;
$http.post('/admin/',{useremail:userEmail, userpassword:userPassword});
}
})
})();
this is the login page html
<!DOCTYPE html>
<html lang="en" >
<head>
<title>Awi Admin</title>
<meta charset="utf-8">
<meta name="description" content="Aplikasi AWI Realtime Lelang Menggunakan Framework ExpressJS dan Realtime Database Firebase">
<meta name="author" content="Muhammad Abubakar Siddiq - MAS Abbe">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel='stylesheet' href='/stylesheets/login.css'/>
<link rel="stylesheet" type="text/css" href="/stylesheets/font-awesome.min.css">>
</head>
<body ng-app="myAdmin">
<div class="container">
<div class="profile">
<button class="profile__avatar" id="btn_avatar">
<img src="/images/avatar.png" alt="Avatar" />
</button>
<div class="profile__form">
<div class="profile__fields">
<h3 class="text-center">Welcome Admin Lelang</h3>
<form name="login-form" role="form" ng-controller="loginCtrl" novalidate>
<div class="fields">
<input type="text" class="input" placeholder="Username" ng-model="user.email" required/>
<span style="color:red" ng-show="login-form.email.$dirty && login-form.user.$invalid">
<span ng-show="login-form.email.$error.required">Username is required.</span>
</span>
</div>
<div class="fields">
<input type="password" class="input" required-pattern=.*\S.* placeholder="password" ng-model="user.password"/>
<span style="color:red" ng-show="login-form.password.$dirty && login-form.user.$invalid">
<span ng-show="login-form.password.$error.required">Password is required.</span>
</span>
</div>
<div class="alert alert-warning" ng-show="login-form.email.$error.email">
<em class="fa fa-lg fa-warning"> </em>Peringatan, username atau password salah
</div>
<div class="profile__footer">
<center>
<button class="btn" id="btn-submit" ng-click="login()">LOG IN</button>
</center>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
document.getElementById('btn_avatar').addEventListener('click',
function () {
[].map.call(document.querySelectorAll('.profile'),
function(el) {
el.classList.toggle('profile--open');
});
}
);
</script>
<script type="text/javascript" src = "/javascripts/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src = "/javascripts/bootstraps/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular-resource.min.js"></script>
<script type="text/javascript" src = "/javascripts/login.js"></script>//==> this is the function for login that call the angular controller
</body>
</html>
and this index.js as server side expressjs
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const engines = require('consolidate');
const path = require('path');
const session = require('express-session');
const bodyParser = require('body-parser');
const app = express();
const firebaseApp = admin.initializeApp(
functions.config().admin
);
const HTTP_SERVER_ERROR = 500;
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing
app.get('/admin/', (req, res)=>{
res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
res.render('index')
});
//this is the functions post for server side express
app.post('/admin/', (req, res)=>{
console.log('post login'+req.body.userEmail, req.body.userPassword);
admin.auth().signInWithEmailAndPassword(req.body.userEmail, req.body.userPassword)
.then(function (user) {
res.render('/admin/home');
console.log("success login admin".user.uid);
})
.catch(function(err){
res.send("fail");
console.log("Error while executing firebase.auth() ",err);
});
});
exports.app = functions.https.onRequest(app);
this my project in github project
my issue for this project is the data from the post function of angular controller to the expressjs post rendering detected as unidentified.
can anyone enlight me what is the cause?? and how to solved this.
this function is naver get to run firebase auth() functions
Try as,
$http({
method: 'POST',
url: '//admin/',
data: {useremail:userEmail, userpassword:userPassword}
}).then(function(rsp){...});
this is the angular controller
(function () {
'usestrict';
"the initialize angular module"
angular.module("myAdmin",[]).controller('loginCtrl', function($scope, $http){
$scope.login = function() {
var userEmail = $scope.user.email;
var userPassword = $scope.user.password;
var myObject = {useremail:userEmail, userpassword:userPassword}
$http({
method: 'POST',
url : '/admin/',
data : JSON.stringify(myObject)
});
}
})
})();
this is the expressjs functions
app.post('/admin/', (req, res)=>{
console.log("####Success");
console.log('post login '+req.body.useremail, req.body.userpassword);
admin.auth().signInWithEmailAndPassword(req.body.useremail, req.body.userpassword)
.then(function (user) {
res.render('/admin/home');
console.log("success login admin".user.uid);
})
.catch(function(err){
res.send("fail");
console.log("Error while executing firebase.auth() ",err);
});
});
after remote desktop consult, final fixed

Angular Routing Causing infinite loop when using parameters in url

I am getting infinite loop when trying to access a parameterized url in angular.
Here is the code.
app.js
var express = require("express");
var cors = require("cors");
var app = express();
app.use(express.static(__dirname));
app.use('/',function(req,res){
res.sendFile("./home.html");
});
app.listen("4467", function() {
console.log("Started listening at port 4467 new");
});
home.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="a02.js"></script>
</head>
<body ng-app="testApp">
Hello Homepage
<div ng-view></div>
</body>
</html>
a02.js
var app = angular.module("testApp", ['ngRoute']);
app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
$routeProvider.when('/test/:a', {
templateUrl: './sum.html',
controller: 'sum'
})
.when("/",{
templateUrl:"./a02.html"
})
.otherwise({
template:"Otherwise"
});
$locationProvider.hashPrefix('');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}]);
app.controller('sum', function($scope, $routeParams) {
console.log("I am controller "+ $routeParams.a);
$scope.a = $routeParams.a;
$scope.b = $routeParams.b;
});
a02.html
Hello there
<hr>
<script> console.log("Getting called again");</script>
Click Me
My requirement is when I click on the Click Me link it should replace the existing ng-view template i.e a02.html to sum.html.
sum.html
<div>
Value of a: {{a}} </br>
Value of b: {{b}}
</div>
But I am getting infinite loop when click on Click Me link.Can someone tell me what I am missing here?

How to get target specific data to render in AngularJS app with Node.js/MongoDB

I'm creating a MEAN stack blog app and what I'm trying to accomplish is getting a "blog" from a list of blogs(div with ng-repeat) which I have saved to my Mongo database using a Mongoose schema to render in a seperate HTML view.
Specifically, I want to be able to click on the <button class="readPost" ng-click="readPost(post._id)">Read Blog</button> in main.html and have that data to be rendered through AngularJS' data-binding in readblog.html.
What I have tried:
1.) I have tried putting a $location.path('/readblog' + id); in the readPost function, but I'm assuming that doesn't work if that path is not specifically declared in my app.js file.
2.) Putting a res.redirect('/readblog'); and a res.redirect('/readblog' + id); in the API call in server.js.
...and now I'm currently looking to see if there are any examples of this problem or alternative methods for achieving this functionality I'm trying to get.
I'm fairly new to coding in general, so I will be happy to clarify on anything that doesn't necessarily make sense here.
Here's what my code looks like:
server.js
//Dependencies.
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var http = require('http');
var path = require('path');
var fs = require('fs');
var port = 9001;
var mongoUri = 'mongodb://localhost:27017/blog-app';
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title : {type: String, min: 8, max: 50, required: true},
body : {type: String, required: true},
author : {type: String, min: 3, max: 40, required: true},
pubdate : {type: Date, default: Date.now}
});
var Blog = mongoose.model('Blog', blogSchema);
app.get('/api/blogs/:blog_id', function(req, res) { //Get Blog by ID.
Blog.find({
_id: req.params.blog_id
}, function(err, blog) {
if (err)
res.send(err);
});
});
mongoose.connect(mongoUri);
mongoose.connection.once('open', function() {
console.log("We are now connected to MongoDB at: ", mongoUri);
});
app.listen(port, function() {
console.log('Listening on port: ', port);
});
mainCtrl.js
var app = angular.module("blog-app");
app.controller('MainController', ['$scope', '$http', '$location', function($scope, $http, $location) {
$scope.apptitle = "AngularJS Blog";
$scope.formData = {};
$http.get('/api/blogs').success(function(data){
$scope.blog = data;
console.log(data);
}).error(function(data) {
console.log('Error: ' + data);
});
$scope.readPost = function(id) {
$http.get('/api/blogs/' + id)
.success(function(data) {
$scope.readblog = data;
console.log('This is the blog you selected: ', data);
});
};
}]);
app.js
var app = angular.module('blog-app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainController'
})
.when('/newblog', {
templateUrl: 'views/newblog.html',
controller: 'MainController'
})
.when('/readblog', {
templateUrl: 'views/readblog.html',
controller: 'MainController'
})
.otherwise({
redirectTo: '/'
});
}) //End Config.
main.html
<div>
<div class="wrapper">
<div class="container" ng-repeat="post in blog">
<p><i class="fa fa-book"></i> {{ post.title }}</p>
<p>by {{ post.author}}</p>
<p>{{ post.pubdate | date }}</p>
<br>
<div>
<p>{{ post.body }}</p>
</div>
<br><br>
<div style="position: absolute; bottom: 10px; right: 10px;">
<button class="deletePost" ng-click="deletePost(post._id)">Delete Blog</button>
<button class="readPost" ng-click="readPost(post._id)">Read Blog</button>
</div>
</div>
</div>
</div>
readblog.html
<div style="padding-top: 150px">
<h2>Title: {{ readblog.title }}</h2>
<h2>Author: {{ readblog.author }}</h2>
<h2>Date: {{ readblog.pubdate }}</h2>
<h2>Body: {{ readblog.body }}</h2>
</div>
What you can do is drop your ngclick and use nghref to navigate to the blog post with selected id, then async load it and and assign it to your blog post scope.
If you have to do it programmatically, use $location and define path for the blog to accept id's.
.when('/readblog/:blogId',...
Similar question
First of all, we need to separate two things; client and server.
Your issue here is about the client side. I suggest you reading through https://github.com/angular-ui/ui-router documentation for your purpose; that is to pass data from one state to another. In your case it is the blogid of the selected blog. Then in your second state, you can retrieve your blogid by $Stateparams and by making a get request to your server to
/api/blogs/:blog_id
Something like
$stateProvider
.state('blog', {
url: "/blogs",
templateUrl: "views/blog.html"
})
.state('readblog', {
url: "/blogs/:blogid",
templateUrl: "views/readblog.html",
params: {
'id':'123456'
})
would do the work.

req.flash weird behaviour with Angular ngRoute

Well, I'm building a simple login page using the MEAN stack. I'm using passport to authenticate, connect-flash to flash messages and Angular ngRoute to, well, route. I have the following code:
app.js
var app = angular.module("app", ["ngRoute"]);
app.factory("appFactory", function($http) {
return {
getData: function(path) {
return $http.get(path)
.then(function(response) {
return response.data;
}, function(response) {
console.log("Error...");
});
}
};
});
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "homeCtrl",
resolve: {
getMessage: function(appFactory) {
return appFactory.getData("/api/login");
}
}
})
.otherwise({
redirectTo: "/"
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
//to fix!
app.controller("homeCtrl", function($scope, getMessage) {
$scope.errors = getMessage.errors;
});
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>My Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.min.js"></script>
</head>
<body>
<!-- ngView -->
<div ng-view></div>
<!-- /ngView -->
<script src="/javascript/angular/app.js"></script>
</body>
</html>
home.html
<form action="/" method="post">
<label>E-mail:</label>
<br/>
<input type="email" name="email" />
<br/>
<label>Password:</label>
<br/>
<input type="password" name="password" />
<br/>
<input type="submit" name="submit" value="Log In" />
</form>
<!-- prints error messages (usually, only one) -->
<span ng-repeat="error in errors">{{errors[$index]}}</span>
login.js
var passport = require("passport");
module.exports = function(app) {
app.get("/api/login", function(req, res) {
var info = {
logged: false,
errors: req.flash("error")
};
if (!req.user) {
console.log(info.errors);
} else {
info.logged = true;
}
res.json(info);
});
}
index.js
var passport = require("passport");
var path = require("path");
module.exports = function(app) {
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "../views/index.html"));
});
app.post("/",
passport.authenticate("local-login", {
successRedirect: "/profile",
failureRedirect: "/",
failureFlash: true
}));
}
So, I'm testing wrong logins, expecting req.flash() to reset after a refresh on the homepage, but it takes some refreshs before resetting. As you can see, I've put a console check when the api is called falsely, and the console outputs:
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
[]
[]
[]
[]
See? It takes some refreshes before cleaning its value. It has nothing to do with my passport authentication strategy nor anything else but the resolve inside the routing. When I attempt to use it without routes (directly on the controller) it works perfectly. Please, help me enlighten my mind on this one and thank you for your time.

Angular.js request/response Node.js

I am trying to request some data from node.js server from my angular.js. The problem is that upon data response i see a blank browser window with my json object printed on it. I want angular.js to recognize the response and stay on page.
HTML form - template that gets loaded with loginController
<section class="small-container">
<div class="login-form">
<form action="/login" method="post" ng-submit="processForm()">
<input ng-model="formData.username" type="text" name="username">
<input ng-model="formData.password" type="password" name="password">
<button>login</button>
</form>
</div>
</section>
Angular.JS
var app = angular.module("blavor", ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "/index",
controller: "loginController"
})
.when("/register", {
templateUrl: "/register",
controller: "registerController"
})
.otherwise("/");
$locationProvider.html5Mode(true);
}]);
app.controller('loginController', function($scope, $http) {
$scope.formData = {};
$scope.processForm = function() {
$http({
method: 'POST',
url: '/login',
data: $.param($scope.formData),
processData: false,
responseType: "json",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
console.log(data);
if (!data.success) {
alert("Noo!");
} else {
alert("YEEEY!");
}
});
};
});
Node.js Server - index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');
var bodyParser = require('body-parser');
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: false }) );
var routes = require('./routes')(app);
http.listen(3000, function() {
console.log('listening on *:3000');
});
module.exports.start = start;
Node.js Server - routes
module.exports = function(app) {
app.post('/login', function(request, response) {
console.log(request.body);
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify({value:"somevalue"}));
});
}
I am using AngularJS v1.2.24 and Node.js v0.10.25
console.log(data) in angular never gets called..
Hi try removing the action and method from your form.
From the ng-submit docs
Enables binding angular expressions to onsubmit events.
Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page), but only if the form does not contain action, data-action, or x-action attributes.
So by adding those, you are causing the page to refresh when the form is submitted.
Without them, angular will call $event.preventDefault() for you, which stops the page from being reloaded.
EDIT: Just to add, you were seeing the correct data from the server because you're responding with preset data, which will always be provided when someone posts to /login.
So your form is currently circumventing angular entirely, and directly getting the data from the server.

Categories

Resources