express-angular-node: Voting Application - angularjs

the following are my two files for a simple voting app and for some reason the button are not increasing the count only when you refresh the voting.html page does both count increase by one. Your help is appreciated.
<!-- voting.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Voting</title>
<script src="angular.min.js"></script>
<script>
var app = angular.module('myFirstApp', []);
app.controller('CounterCtrl', function($scope,$http) {
console.log('CounterCtrl started');
// $scope.countA = 0;
// $scope.countB = 0;
// $scope.Acrease = function() {
// console.log('Acrease() called');
// $scope.countA++;
// };
// $scope.Bcrease = function() {
// console.log('Bcrease() called');
// //if($scope.count>0) $scope.count--;$scope.count++;
// $scope.countB++;
// };
function getItemsA() {
$http.get('/voteA').then(function(res) {
$scope.countA = res.data;
//$scope.countA = res.json(A);
console.log('/voteA: ', $scope.countA);
});
}
getItemsA();
function getItemsB() {
$http.get('/voteB').then(function(res) {
$scope.countB = res.data;
//$scope.countA = res.json(A);
console.log('/voteB: ', $scope.countB);
});
}
getItemsB();
// $scope.addItem = function() {
// console.log('addItem()\t newItem=', $scope.newItem);
// $http.get('/list/add/' + $scope.newItem).then(getItems);
// };
});
</script>
</head>
<body ng-app="myFirstApp">
<div ng-controller="CounterCtrl">
<p>Count of A Vote: <b>{{countA}}</b></p>
<p>Count of B Vote: <b>{{countB}}</b></p>
<input type="button" ng-click="getItemsA()" value="A">
<input type="button" ng-click="getItemsB()" value="B">
</div>
</body>
</html>
/***server.js***/
var express = require('express');
var app = express();
app.listen(3001, function() {
console.log('Listening on 3001');
});
// Mount the public directory at /
app.use('/', express.static('./public'));
/********************************************
* This code is for voting.html
*******************************************/
// initialize the votes variables
var A = 0 ;
var B = 0 ;
// add the voteA
app.get('/voteA', function(req,res) {
//res.json(A);
A++
res.json(A);
});
// add the voteB
app.get('/voteB', function(req,res) {
//res.json(A);
B++
res.json(B);
});

This is angular1 I presume.
I think your problem is that your ng-click is calling a function which is not in scope. I believe you should create scope functions:
$scope.getItemsA = function() {
$http.get('/voteA').then(function(res) {
$scope.countA = res.data;
console.log('response recieved');
});
};
Hope it helps..

Related

AngularJs with REST Api

i'm new to angularJs and want to learn more about it, i'm trying to display some users from a fake REST Api, when trying to run my code i got empty page and the console doesn't give me any errors , i don't know where is the error or where i can debug.
app.js
var myApp = angular.module("app", []);
contactsData.service.js look like that :
(function () {
var app = angular.module("app");
app.service("contactDataSvc", function ($http) {
var self = this;
self.getContacts = function () {
var promise1 = $http.get("http://localhost:3000/contacts");
var promise2 = promise1.then(function (response) {
return response.data;
});
return promise2;
}
});
})();
contacts.controller.js
(function () {
var myApp = angular.module("app");
myApp.controller("contactsCtrl", contactsCtrl);
function contactsCtrl(contactDataSvc) {
contactDataSvc.getContacts()
.then(function(data){
this.contacts = data;
});
}
})();
finally my view index.html
<html ng-app="app">
<head>
<title></title>
<script src="angular.js"></script>
<script src="app.js"></script>
<script src="contacts.controller.js"></script>
<script src="contactsData.service.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />
<!--<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>-->
</head>
<body class="container">
<div>
<div ng-controller="contactsCtrl as ctrl">
<div class="raw">
<ul class="list-group">
<li class="li-group-item" ng-repeat="obj in ctrl.contacts">
{{obj.name.title + " " + obj.name.first + " " + obj.name.last}}
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
Small correction required in your contactsCtrl
function contactsCtrl(contactDataSvc) {
var vm = this;
contactDataSvc.getContacts()
.then(function(data){
vm.contacts = data;
});
}
You cannot use this inside the then callback as the scope will be different.
Corrected working example here : http://plnkr.co/edit/LLKJipkBbiZ17QjQpw1X
Refer more:
https://www.w3schools.com/js/js_scope.asp
What is the scope of variables in JavaScript?
1 - Is this url correct? http://localhost:3000/contacts
2 - Open the url on any browser, does it return any response ? JSON?
Please check this first to see if the problem is not on the server side.
Firstly inject $scope in controller because anything/data that we want to access over Html from controller needs to be binded on $scope.
So you controller would look like:
(function () {
var myApp = angular.module("app");
myApp.controller("contactsCtrl", contactsCtrl);
function contactsCtrl($scope,contactDataSvc) {
contactDataSvc.getContacts()
.then(function(data){
$scope.contacts = data;
});
}
})();
Secondly from the service you need to return a promise from it only then you will be able to get the data once the response is back from the API.
So,the updated service code is :
(function () {
var app = angular.module("app");
app.service("contactDataSvc", function ($http,$q) {
var self = this;
var defered = $q.defer();
self.getContacts = function () {
var promise1 = $http.get("http://localhost:3000/contacts");
promise1.then(function (response) {
defered.resolve(response.data);
});
return defered.promise;
}
});
})();

Angular login auth what about using web worker?

What do you think about this approach
using web worker for angular login/auth
it looks good at me and in this way you can get rid of
$rootScope event as well :)
This is just an example in a more prodution way
you should use like https://stackoverflow.com/a/16730809
Html & js
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Form</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body ng-controller="LoginController as vm">
<p ng-if="vm.isLogged">Logged as {{vm.username}}</p>
<a href ng-click="vm.doFakeLogin()">Login</a>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.2/angular.min.js">
</script>
<script>
function LoginController($scope){
var vm = this;
vm.isLogged = false;
var workerCheckLogin = new Worker('worker-check-login.js');
var workerDoLogin = new Worker('worker-do-login.js');
var jwt = 'auth-token';
workerCheckLogin.postMessage(jwt);
workerCheckLogin.addEventListener('message', function(e) {
if(e.data > 0){
$scope.$evalAsync(function() {
vm.isLogged = true;
vm.username = 'Whisher';
});
}
}, false);
vm.doFakeLogin = function doFakeLogin(){
workerDoLogin.postMessage({username:'whisher','password':'12345'});
}
workerDoLogin.addEventListener('message', function(e) {
if(e.data > 0){
$scope.$evalAsync(function() {
vm.isLogged = true;
vm.username = 'Whisher';
});
}
}, false);
}
angular
.module('app', [])
.controller('LoginController',LoginController);
</script>
</body>
</html>
worker-check-login.js
self.addEventListener('message', function(e) {
console.log('Worker check login said: ', e.data);
/*
do xhr to the server
e.data = jwt
return
1 succees
0 fail
*/
self.postMessage(0); //
}, false);
worker-do-login.js
self.addEventListener('message', function(e) {
console.log('Worker do login said: ', e.data);
/*
do xhr to the server
e.data = credentials
return
1 succees
0 fail
*/
self.postMessage(1); //
}, false);

Angularjs, the controller can't read from the factory?

I have a services.js file where I placed my facotry:
.factory('dataShare',function($rootScope){
var service = {};
service.data = false;
service.sendData = function(data){
this.data = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.data;
console.log('this.data')
};
return service;
})
And my controllers, in the controller.js file look like this:
.controller('recommendedJobsCtrl', function($q,$scope, $ionicSideMenuDelegate,$window,$http,dataShare) {
$scope.text='hey';
$scope.post=function(){
dataShare.sendData($scope.text);
console.log('here')
}
})
.controller('jobPostCtrl', function($scope,$ionicSideMenuDelegate,dataShare) {
$scope.text = '';
$scope.$on('data_shared',function(){
var text = dataShare.getData();
$scope.text = text;
console.log(text)
});
})
When I did console.log, i realized that the service.getData isn't wokring, i.e the receiving controller (jobPostCtrl) isn't getting anything.
How can i fix this?
Here is example that works.
<!doctype html>
<html>
<head>
<title>AngularJS</title>
<script src="angular.min.js"></script>
<script type="text/javascript">
var sampleApp = angular.module('sampleApp', []);
sampleApp.factory('dataShare',function($rootScope){
var service = {};
service.data = false;
service.sendData = function(data){
this.data = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.data;
console.log('this.data')
};
return service;
});
sampleApp.controller('recommendedJobsCtrl', function($q,$scope,$window,$http,dataShare) {
$scope.text='hello world!';
$scope.post=function(){
dataShare.sendData($scope.text);
console.log('sent: ' + $scope.text);
}
});
sampleApp.controller('jobPostCtrl', function($scope,dataShare) {
$scope.text = '';
$scope.$on('data_shared',function(){
var text = dataShare.getData();
$scope.text = text;
console.log('received: ' + $scope.text);
});
});
</script>
</head>
<body ng-app="sampleApp">
<div ng-controller="recommendedJobsCtrl">
<input type="text" ng-model="text" />
<button ng-click="post()">Send</button>
</div>
<div ng-controller="jobPostCtrl">
<p>{{text}}</p>
</div>
</body>
</html>
Use
$rootScope.$broadcast('data_shared',this.data);
and $scope.$on('data_shared',function(event,data){
$scope.$scope.text=data;
});

Ionic/AngularJS & Wordpress API

I'm somewhat new to the JS world, so I'm struggling a bit as to what I did wrong. My sample data from wordpress API is not working. Any ideas what I did wrong:
app.controller('FeedCtrl', function($http, $scope, $ionicLoading) {
console.log("Loading FeedCtrl");
$scope.stories = [];
function loadStories(params, callback) {
$http.get('http://public-api.wordpress.com/rest/v1/freshly-pressed/', {params: params})
.success(function(response) {
var stories = [];
angular.forEach(response.data.children, function(child) {
stories.push(child.data);
});
callback(stories);
});
}
$scope.loadOlderStories = function() {
var params = {};
if ($scope.stories.length > 0) {
params['after'] = $scope.stories[$scope.stories.length - 1].name;
}
loadStories(params, function(olderStories) {
$scope.stories = $scope.stories.concat(olderStories);
$scope.$broadcast('scroll.infiniteScrollComplete');
});
};
$scope.loadNewerStories = function() {
var params = {'before': $scope.stories[0].name};
loadStories(params, function(newerStories) {
$scope.stories = newerStories.concat($scope.stories);
$scope.$broadcast('scroll.refreshComplete');
});
};
I've made a simplified example with your data.
Click the 'Load more' button to retrieve some posts. You should see a list with the title and the author of a post.
EDIT: There appears to be some cross-domain request issues, that's why the 'Load stories' button won't work. Just try to reflect this code inside your controller, it should work.
var app = angular.module('myApp', []);
app.controller('feedCtrl', function ($scope, $http) {
$scope.stories = [];
$scope.loadStories = function loadStories() {
console.log('loading stories');
$http.get('http://public-api.wordpress.com/rest/v1/freshly-pressed/')
.then(function onSuccess(response) {
console.log(response);
$scope.stories = response.data.posts;
}, function onFailed(error) {
console.error('Error:', error)
});
}
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="feedCtrl">
<button data-ng-click="loadStories()">Load stories</button>
<ul>
<li data-ng-repeat="story in stories">Title: {{ story.title }} - {{ story.author.first_name }} {{ story.author.last_name }}</li>
</ul>
</div>
</body>
</html>
Normally we wouldn't handle $http calls in our angular.controller. This needs to be done in an angular.service.

Phonegap.js on second html page

I basically have two pages in my phonegap application that I am building with PGB (index.html and main.html), that both use angular.js. Index.html is a login for the app, which redirects to main.html afterwards. All my plugins and phonegap.js are being injected fine into main, but none of the inline JS (alerts on doc ready, device ready, window load) are firing, let alone phonegap.js being loaded as well.
Any advice would be appreciated.
Script Includes:
<script src="phonegap.js"></script>
<script src="cdv-plugin-fb-connect.js"></script>
<script src="facebook-js-sdk.js"></script> <script>alert("inside pg");</script>
<script src="childbrowser.js"></script>
<script src="js/jquery.js"></script>
<script src="js/angular.min.js"></script>
<script>alert("here");</script>
<script src="js/controllers.js"></script>
<script src="js/klass.min.js"></script>
<script src="js/code.photoswipe.jquery-3.0.5.min.js"></script>
<script src="js/maskedInput.js" type="text/javascript"></script>
<script src="js/jquery.joyride.js"></script>
<script src="js/jquery.fancybox.pack.js"></script>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
Scripts:
alert("p2 adding")
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
alert("main.html: device is ready");
}
$(window).load(function(){
alert("window.load happening");
})
</script>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-42023187-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-42023187-1', 'openvino.com');
ga('send', 'pageview');
</script>
<script type="text/javascript">
var objectToLike = window.location;
var FBactivated = false;
FB.init({
appId : '659381964079214', // App ID
channelURL : '', // Channel File, not required so leave empty
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true,
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
getFriends();
testAPI();
FBactivated = true;
}
});
function getFriends() {
var fbUserIDs = []
FB.api('/me/friends', function(response) {
if(response.data) {
$.each(response.data,function(index,friend) {
var id = friend.id;
fbUserIDs.push(id);
});
var dataString = "fbUserIDs="+fbUserIDs.join();
$.ajax({
type: "POST",
data: dataString,
async: false,
url: "http://m.openvino.com/Scripts/faveMatch.php"
}).done(function(data){
console.log(data);
window.localStorage.setItem("fbFriends", data);
console.log("Saved");
});
} else {
alert("Error!");
}
});
}
function testAPI() {
FB.api('/me', function(response) {
//console.log(response, response.email);
var dataString2 = "id=" + response.id;
dataString2 += "&first_name=" + response.first_name;
dataString2 += "&last_name=" + response.last_name;
dataString2 += "&email=" + response.email;
console.log(dataString2);
$.ajax({
type: "POST",
url: "http://m.openvino.com/Scripts/fbconnect.php",
data: dataString2
}).done(function(data){
var dataJSON = $.parseJSON(data);
if (dataJSON[0].STATUS == "FAILURE") {
//console.log(dataJSON[0].MESSAGE);
return false;
} else if (dataJSON[0].STATUS == "SUCCESS") {
window.localStorage.setItem('email',dataJSON[0].COOKIE.email);
window.localStorage.setItem('password',dataJSON[0].COOKIE.password);
window.localStorage.setItem('name_first',dataJSON[0].COOKIE.name_first);
window.localStorage.setItem('name_last',dataJSON[0].COOKIE.name_last);
window.localStorage.setItem('uID',dataJSON[0].COOKIE.uID);
window.localStorage.setItem('phone',dataJSON[0].COOKIE.phone);
window.localStorage.setItem('firstTime',dataJSON[0].COOKIE.firstTime);
}
});
});
}
function fbLogout() {
if (FBactivated) {
try {
FB.logout(function(response) {
window.location.href = "index.html";
});
} catch (err) {
window.location.href = "index.html";
}
} else {
window.location.href = "index.html";
}
}
$(document).ready(function() {
alert("document.ready loaded");
$("#logmeout").click(function(e){
e.preventDefault();
window.localStorage.clear();
fbLogout();
return false;
});
$('.back_btn').click(function(e) {
$('.profile_menu').hide();
history.back();
});
$(document).click(function(e) {
$('.profile_menu').hide();
})
$('.profile_btn').click(function(e) {
$('.profile_menu').slideToggle();
e.stopPropagation();
e.preventDefault();
return false;
});
$('.profile_menu a').each(function() {
$(this).click(function(e) {
$('.profile_menu').hide();
});
});
});
HTML:
<body ng-app="OpenVino">
<div id="fb-root"></div>
<div class="header-wrap">
<header>
<div ng-show="(page != 'list')" class="back_btn"></div>
<img src="imgs/logo_only.png" alt="OpenVino" />
<div class="profile_btn"></div>
</header>
</div>
<div class="profile_menu">
My Favorites
Contact OpenVino
Images
Logout
</div>
<div class="content {{page}}" ng-view></div>
I fixed it with a simple, but disheartening solution: You have to turn your multipage app into a one page app. Unfortunate how phonegap advertises that you can take your HTML, CSS, and JS and build it natively. All of the .js loaded on the second page wouldnt work until I changed my login to a partial and fooled around with the routing.

Resources