put facebook login data into textfields with angualrjs - javascript

I'm implementing facebook login and its working alright with angular.but the problem is when i get the data from facebook i'm unable to put in a textfield. when i put it in an alert its able to give me the data but can't put it in a textfield.
<div ng-controller="facebook_login">
<p align="center"><button class="icon icon-left ion-social-facebook button button-positive button-small" ng-click="fbLogin()">Sign Up with Facebook</button></p>
<div class="list">
<div class="item">
<label class="item item-input item-stacked-label">
<span class="input-label">Fashion Line</span>
<input type="text" ng-model="email" ng-value="{{data.email}}" />
<div>
JS
.controller('facebook_login',['$scope', '$ionicModal', '$timeout', 'ngFB', function($scope, $ionicModal, $timeout, ngFB) {
$scope.fbLogin = function () {
ngFB.login({scope: 'email,public_profile,publish_actions'}).then(
function (response) {
if (response.status === 'connected') {
//alert('Facebook login succeeded, got access token: ' + response.authResponse.accessToken);
//$scope.closeLogin();
ngFB.api({
path: '/me',
params: {fields: 'first_name,last_name,gender,email,picture'}
}).then(
function (data) {
$scope.facebook = data;
alert(data.email)
$scope.email = $scope.data.email;
document.getElementById("email").innerHTML = data.email;
});
} else {
alert('Facebook login failed');
}
});
};
}])

Seems like you never defined $scope.data but you're trying to use it. Did you mean $scope.facebook.email instead?

Related

Angular ng-click cannot get value of ng-model

I am working with a form and I literally just want to get the value from an ng-model. the form looks like this:
<form name="comment_form" class="row" novalidate>
<div class="col col-80 content col-center">
<input class="new-comment-message" type="text" style="margin-left: 15px;" placeholder="Leave a comment..." ng-model="new_comment" required></input>
</div>
<div class="col col-20 button-container col-center">
<button class="button button-clear send" type="submit" ng-click="addComment()" ng-disabled="comment_form.$invalid">
Send
</button>
</div>
</form>
This is my whole controller. The end result is to post a comment to wordpress however With my form content returning undefined its a bit difficult. (P.S. its posting to wordpress and the comment is just saying 'undefined'):
.controller('EasternInnerCtrl', function ($http, $timeout, $scope, $ionicLoading, $stateParams, $ionicScrollDelegate, $cordovaSocialSharing, $ionicModal, Easternc, AuthService) {
$scope.eastc = Easternc.get($stateParams.eastcId);
$ionicModal.fromTemplateUrl('commenter.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal
})
$scope.openModal = function() {
$scope.modal.show()
}
$scope.closeModal = function() {
$scope.modal.hide();
};
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
$scope.addComment = function(){
$ionicLoading.show({
template: 'Submiting comment...'
});
console.log($scope.new_comment);
Easternc.submitComment($scope.eastc.id, $scope.new_comment).then(function(data){
if(data.status=="ok"){
var user = AuthService.getUser();
var comment = {
author: {name: user.data.username},
content: $scope.new_comment,
date: Date.now(),
user_gravatar : user.avatar,
id: data.comment_id
};
console.log($scope.new_comment);
/*$scope.eastc.comments.push(comment);
console.log(comment);
$scope.new_comment = "";
$scope.new_comment_id = data.comment_id;
$ionicLoading.hide();
$ionicScrollDelegate.scrollBottom(true);*/
}
});
};
$scope.sharePost = function(link){
console.log(link);
window.plugins.socialsharing.share('I just read this article on blah: ', null, null, url);
};
})
my console log is showing: undefined when I click send though?
I'm pretty sure the modal got an isolated scope. It means $scope.new_comment wont exists in your controller.
You should try this :
$scope.addComment = function(comment){
Easternc.submitComment($scope.eastc.id,comment).then(function(data){
console.log(comment);
});
};
with this in your html
<button class="button button-clear send" type="submit" ng-click="addComment(new_comment)" ng-disabled="comment_form.$invalid">
Send
</button>
Hope it helped.

Cordova Ionic refresh side menu after log in and log out

I'm trying to automatically reload my side menu after I log in and log out. I'm doing that by checking my window.localStorage. I've experienced that the side menu won't reload/refresh after I do the action login or logout.
I'm using $state.go('tabs.home') to navigate to another page, but my side menu won't refresh.
Below here is my code:
navCtrl:
app.controller('NavCtrl', function ($scope, $ionicSideMenuDelegate, $rootScope) {
$scope.showMenu = function () {
$ionicSideMenuDelegate.toggleLeft();
};
$scope.showRightMenu = function () {
$ionicSideMenuDelegate.toggleRight();
};
var data = JSON.parse(window.localStorage.getItem("currentUserData"));
if (data != null) {
if (data["id_gebruiker"] == null) {
$rootScope.control = {
showLogin: false,
showLogout: true
};
}
else {
$rootScope.control = {
showLogin: true,
showLogout: false
};
}
}
})
navHtml:
<ion-side-menu-content ng-controller="NavCtrl">
<ion-nav-bar class="bar-positive">
<ion-nav-back-button class="button-icon ion-arrow-left-c">
</ion-nav-back-button>
<ion-nav-buttons side="left">
<button class="button button-icon button-clear ion-navicon" ng-click="showMenu()">
</button>
</ion-nav-buttons>
<ion-nav-buttons side="right">
<button class="button button-icon button-clear ion-ios7-gear" ng-click="showRightMenu()">
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-nav-view animation="slide-left-right"></ion-nav-view>
</ion-side-menu-content>
loginCtrl:
app.controller('LoginCtrl', function ($scope, $http, $state) {
/*
* This method will be called on click event of button.
* Here we will read the email and password value and call our PHP file.
*/
$scope.check_credentials = function () {
//document.getElementById("message").textContent = "";
$http({ method: 'GET', url: 'http://localhost:34912/api/gebruikers?email=' + $scope.email + '&wachtwoord=' + $scope.wachtwoord }).success(function (data) {
bindUserData(data);
//window.location.reload();
$state.go('tabs.about');
});
function bindUserData(data) {
//alert(JSON.stringify(data));
window.localStorage.setItem("currentUserData", JSON.stringify(data));
}
}
});
app.controller('LogoutCtrl', function ($scope, $http, $state) {
/*
* This method will be called on click event of button.
* Here we will read the email and password value and call our PHP file.
*/
$scope.logout = function () {
var data = JSON.parse(window.localStorage.getItem("currentUserData"));
if (data != null) {
window.localStorage.removeItem("currentUserData");
$state.go('tabs.home');
}
}
});
loginHtml:
<ion-view title="Login">
<ion-content>
<form id="loginForm" ng-app="ionicApp" ng-controller="LoginCtrl">
<div class="list">
<label class="item item-input">
<span class="input-label">Email</span>
<input ng-model="email" type="text" placeholder="Username" />
</label>
<label class="item item-input">
<span class="input-label">Wachtwoord</span>
<input ng-model="wachtwoord" type="password" placeholder="***********" />
</label>
</div>
<div class="padding">
<input type="submit" value="Log on" ng-click="check_credentials()" class="button button-block button-positive" />
</div>
</form>
</ion-content>
I hope you'll understand my problem. I also tried to do a window.location.reload() before $state.go, but that looks buggy. Are there some best practices to fix my problem? Please help me!
Greetings.
Look at the accepted solution at https://stackoverflow.com/a/30524540/1376640
Relevant part of the code is:
$scope.logout = function () {
$ionicLoading.show({
template: 'Logging out....'
});
$localstorage.set('loggin_state', '');
$timeout(function () {
$ionicLoading.hide();
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
$ionicHistory.nextViewOptions({
disableBack: true,
historyRoot: true
});
$state.go('login');
}, 30);
};
Worked for me.
Not a Angular expert but I think that your page will have rebuilt before the $http.get has finished. I got round this by raising an event so where you call bindUserData in the get success change that to $scope.$emit('event', data) then handle the update in a $scope.$on('event'. data). Cut down version of my code below.
controller('AppCtrl', function($scope, $ionicModal, $timeout, MenuData, Data, $ionicActionSheet, UserData, $state, SessionStorage) {
$scope.$on('menuDataChange', function (event, data) {
//refresh menu items data
$scope.items = data;
//clear the state
$state.go($state.current, {}, { reload: true });
});
$scope.items = Data.getItems(SessionStorage.isAuthenticated());
// Form data for the login modal
$scope.loginData = {};
$scope.doLogout = function () {
SessionStorage.clear();
$scope.$emit('menuDataChange', Data.getItems(false)); //Get the menu items for unauthenticated users and raise the change event
};
// Perform the login action when the user submits the login form
$scope.doLogin = function () {
console.log('Doing login', $scope.loginData);
UserData.async($scope.loginData.username, $scope.loginData.password, '12345').then(
// successCallback
function () {
data = UserData.getAll();
var expirationDate = new Date();
expirationDate.setTime(new Date().getTime() + 1200000); //20 minutes
SessionStorage.save({ serverAuthToken: data.d.Items[0].ServerAuthToken, expirationDate: expirationDate });
$scope.$emit('menuDataChange', Data.getItems(true)); //get the menu items for authenticated users and raise the change event
console.log(data);
$state.go('app.home', {}, { reload: true });
},
// errorCallback
function () {
console.log('userdate error');
},
// notifyCallback
function () { }
);
};
})

Angularjs: View not updating list after POST

I am currently working on a small angularjs app which is basically a user profile management app.
The problem i am having is with adding users dynamically. When i enter the user data, it successfully POST's to my local server i have setup, BUT i have to refresh the page to see the new user in the users list
I obviously dont want to have to refresh.
-Yes i've tried $scope.apply() after running the POST function
Something i am noticing with Angular Batarang (Debugging tool), is that the scope is updating fine, but there is a blank spot or 'null' value where the new user should be.
Here are the Controllers:
UsersApp.controller('UserListController', [ '$scope', 'userService', function($scope, userService) {
$scope.usersList = userService.usersList;
$scope.users = userService.users;
$scope.user = userService.user;
}]);
UsersApp.controller('AddUserController', function($scope, $window, dataResources, userService) {
$scope.addNew = function addNew(newUser) {
$scope.usersList = userService.usersList;
var firstName = newUser.firstName;
var lastName = newUser.lastName;
var phone = newUser.phone;
var email = newUser.email;
$scope.newUserData = {
firstName , lastName, phone , email
}
new dataResources.create($scope.newUserData);
$scope.usersList.push(dataResources);
$scope.$apply();
};
And Here are my views:
Add User:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="js/minimize.js"></script>
<div ng-controller="AddUserController">
<div class="userInfo" id="usernameDiv">
<h2 id="username">User<img id="showhide" src="images/plus.png" style="position:absolute; padding-left:15px; width:31px; color:white;"></h2>
</div>
<div class="userInfo">
<div id="listInfo">
<form ng-controller="AddUserController">
<input type="text" placeholder= "First Name" ng-model="newUser.firstName"></input>
<input type="text" placeholder= "Last Name" ng-model="newUser.lastName"></input>
<input type="text" placeholder= "Phone Number" ng-model="newUser.phone"></input>
<input type="text" placeholder= "Email" ng-model="newUser.email"></input>
<button type="submit" ng-click="addNew(newUser)">Add User</button>
</form>
</div>
</div>
Users List:
<!DOCTYPE html>
<html>
<head></head>
<body id="">
<div ng-controller="UserListController">
<div class="userInfo">
<h2>List of Users</h2>
<div id="listInfo">
<ul style="list-style-type: none;">
<li ng-repeat="user in usersList">
<!--<p class="userData">ID: {{ user }}</p> -->
<p class="userData"><a style="cursor:pointer;" ui-sref="UserProfile">{{ user.firstName }}</a></p>
</li>
</ul>
</div>
</div>
Factory and Service:
UsersApp.factory('dataResources', [ '$resource', function($resource) {
return $resource('http://localhost:24149/users/:id', {}, {
query: {method:'GET', params:{idnum: '#id'}, isArray:true},
create: {method:'POST', headers: { 'Content-Type': 'application/json' }},
update: {method:'PUT', params:{idnum: '#id'}},
remove: {method:'DELETE', params:{idnum:'#id'}, isArray:true}
});
}]);
UsersApp.service('userService', function(dataResources) {
return {
usersList: dataResources.query()
}
});
I'm not sure if I follow exactly, but I believe you need to deal with a promise from your POST and then push the result. e.g.,
dataResources.create($scope.newUserData).$promise.then(function(data) {
$scope.usersList.push(data);
});
Your service will return a promise and then when the POST is complete your service should return the new user and you just add it to your current list.
See $resource documentation:
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
According to the doc your code should look like this:
dataResources.create($scope.newUserData,
function(data) {
$scope.usersList.push(data);
}
);
controller: you don't need to make a new userdata object, you can just use newUser
UsersApp.controller('AddUserController', function($scope, $window, dataResources, userService) {
$scope.usersList = userService.usersList;
$scope.addNew = function addNew(newUser) {
dataResources.create($scope.newUser,
function(data) {
$scope.usersList.push(data);
}
);
};
};
Same idea for angular2 using observables.
public posts: any;
onPost(input) {
this.dataService.jsonserverPost(input)
.subscribe(
(data: any) => {
this.posts.push(data);
}
);
}

ng-click function immediately executing function without clicking

I am new to angular and trying to setup a login system. I have some 'buttons' setup to redirect users to an Oauth prompt to users facebook/google account when the button is clicked. My problem is that the function to log users in is executing immediately on page log and not when the button is clicked.
I am pretty sure the root lies in the way JS objects work but I am still learning angularjs and it is a bit confusing.
I believe that putting the functions on the $scope will execute them immediately but I don't see how else I can expose them to the ng-click.
Could someone help me work out how to make the buttons work as expected?
template:
<ion-view title="Account">
<ion-nav-buttons side="right">
<button menu-toggle="right" class="button button-icon icon ion-navicon"></button>
</ion-nav-buttons>
<ion-content class="has-header padding">
<h1 ng-click="google_login()">Log in with Google</h1>
<h1 ng-click="fb_login()">Log in with Facebook</h1>
<h1 ng-click="dev_login()">Dev login</h1>
<div id="logs"></div>
<form class="list">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="user.username" required>
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="user.password" required>
</label>
<div class="padding">
<button class="button button-block button-stable" ng-click="email_authenticate()">Login</button>
</div>
</form>
</ion-content>
</ion-view>
controller:
.controller('AccountCtrl', function($scope, $state, Authentication) {
$scope.dev_login = Authentication.dev_authenticate(); //executes immediately
$scope.fb_login = Authentication.fb_authenticate(); //executes immediately
$scope.google_login = Authentication.google_authenticate(); //executes immediately
$scope.email_login = Authentication.email_authenticate(); //executes immediately
$scope.logout = Authentication.logout();
});
These are defined in services.js:
.factory('Authentication', function ($http) {
return {
authenticate: function () {
return $http({
url: 'https://api.squawkfinace.com/authenticate',
method: 'post'//,
//data: {facebook_authtoken: key}
});
},
fb_authenticate: function () {
return $.oauth2({
//Oauth details
}, function (token, response) {
localStorage.setItem("LoggedInAccount", JSON.stringify({'platform': 'facebook', 'token': token}));
console.log(token);
$state.transitionTo("app.notifications");
}, function (error, response) {
// do something with error object
});
},
google_authenticate: function () {
return $.oauth2({
//oauth details
}, function (token, response) {
localStorage.setItem("Account", JSON.stringify({'platform': 'google', 'key': token}));
}, function (error, response) {
// do something with error object
$("#logs").append("<p class='error'><b>error: </b>" + JSON.stringify(error) + "</p>");
$("#logs").append("<p class='error'><b>response: </b>" + JSON.stringify(response) + "</p>");
});
},
dev_authenticate: function () {
return null;
},
email_authenticate: function () {
return null;
},
logout: function () {
localStorage.removeItem("Account");
return null;
}
}
});
It's because you're actually executing the functions
$scope.dev_login = Authentication.dev_authenticate();
should be
$scope.dev_login = Authentication.dev_authenticate;
The first scenario executes the function and assigns the result to $scope. You want to assign the reference to the function instead.

TypeError: this.mRef.auth is not a function

Back again with a new type error. Working on authentication right now. Working with AngularJS and firebase. Right now when I run my function on click of the submit button I get this in my console "TypeError: this.mRef.auth is not a function". I'm thinking it's something simple but here is my login controller:
.controller('Login', ['$scope', 'angularFire',
function($scope, angularFire) {
$scope.signin = function(){
var ref = "https://myappurl.firebaseio.com";
var auth = new FirebaseAuthClient(ref, function(error, user) {
if (user) {
// user authenticated with Firebase
console.log(user);
} else if (error) {
// an error occurred authenticating the user
console.log(error);
} else {
// user is logged out
console.log("hello");
}
});
console.log($scope);
var user = $scope.cred.user;
var pass = $scope.cred.password;
auth.login('password', {
email: user,
password: pass,
rememberMe: false
});
}
}])
Next is the html. I have it inside a controller called login and here is what is in it:
<div class="inner loginbox" ng-controler="Login"
<fieldset>
<label class ="white">Username</label>
<input type="text" id="username" ng-model="cred.user">
<span class="help-block"></span>
<label class ="white">Password</label>
<input type="password" id="password" ng-model="cred.password">
<div class="centerit rem-me">
<label class="checkbox">
<div class="white">Remember me?
<input type="checkbox" ng-model="cred.remember">
</div>
</label>
</div>
<div class="spacer1">
</div>
<a class="btn btn-inverse btn-large btn-width" id="signupsubmit" ng-click="signin()">Sign in</a>
</fieldset>
</div>
The type error I get refers to firebase-auth-client.js on line 79. In chrome I have this in the console: Uncaught TypeError: Object https://kingpinapp.firebaseio.com has no method 'auth'
When instantiating the FirebaseAuthClient, you should pass an actual Firebase reference, not just the string representation of one.
Updating your code to use the following snippet should fix your problem:
var ref = new Firebase("https://myappurl.firebaseio.com");
var auth = new FirebaseAuthClient(ref, function(error, user) {

Categories