ReferenceError: fblogin is not defined at new LoginController - Angular - javascript

I'm trying to add a simple login via facebook but I'm having some trouble.
.js file:
(function () {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['$location', 'AuthenticationService', 'FlashService'];
function LoginController($location, AuthenticationService, FlashService) {
var vm = this;
vm.login = login;
vm.fblogin = fblogin;
(function initController() {
// reset login status
AuthenticationService.ClearCredentials();
})();
fblogin = function(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
function login() {
vm.dataLoading = true;
AuthenticationService.Login(vm.username, vm.password, function (response) {
if (response.success) {
AuthenticationService.SetCredentials(vm.username, vm.password);
$location.path('/');
} else {
FlashService.Error(response.message);
vm.dataLoading = false;
}
});
};
}
})();
And the .html:
<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" ng-submit="vm.login()" role="form">
<div class="form-group" ng-class="{ 'has-error': form.username.$dirty && form.username.$error.required }">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" ng-model="vm.username"/>
<span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required }">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" ng-model="vm.password" />
<span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
</div>
<button ng-click="vm.fblogin()">Facebook Login</button>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary">Login</button>
<img ng-if="vm.dataLoading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
Register
</div>
</form>
</div>
the only part that really matter in the html is this one:
<button ng-click="vm.fblogin()">Facebook Login</button>
And I'm getting this error:
ReferenceError: fblogin is not defined
at new LoginController

Make sure you have the correct APP id and the redirect url set in the app settings.
.config([
'FacebookProvider',
function(FacebookProvider) {
var myAppId = '1367223633302978';
FacebookProvider.init(myAppId);
}
])
DEMO

Related

AngularJS 1.6.8: Unable to submit form and display success message

I have a simple query submission form with name, email and query fields and a component with a controller function having the submit function to submit the form.
I am using ng-submit directive in the <form></form> tag to submit the user input and display a success message on submission.
below is the code for the respective files.
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div>
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService,$rootScope) {
var vm = this;
$scope.navigate = function(home){
$state.go(home)
};
$scope.saveform = function(){
$scope.name= vm.name;
$scope.email= vm.email;
$scope.query= vm.email;
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted."
};
$scope.user = userService;
};
//localStorage code
function userService($rootScope) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
UPDATE: On Submit, When I check the response in network tab in dev tools, I do not see the submitted values. All I see is the markup.
In your template, the name of the method is saveform:
ng-submit="saveform()"
But in your controller, it's save:
$scope.save = function() { ... }
Rename it to saveform:
$scope.saveform = function() { ... }

Angular Not Posting to URI

My angular code is not posting to the api when I enter data in a form even though my api has been proven to work and takes curl CRUD requests. The register function is called from my partial, then Register controller uses the user service and register function to post form the model to the api
user service
(function () {
'use strict';
angular
.module('app')
.factory('UserService', UserService);
UserService.$inject = ['$http'];
function UserService($http) {
var service = {};
service.GetAll = GetAll;
service.GetById = GetById;
service.GetByUsername = GetByUsername;
service.Create = Create;
service.Update = Update;
service.Delete = Delete;
return service;
function GetAll() {
return $http.get('https://me.com/api/users/').then(handleSuccess, handleError('Error getting all users'));
}
function GetById(id) {
return $http.get('https://me.com/api/users/' + id).then(handleSuccess, handleError('Error getting user by id'));
}
...
function Create(user) {
return $http.post('https://me.com/api/users', user).then(handleSuccess, handleError('Error creating user'));
}
.....
Register Partial
<div ng-controller="RegisterController as vm">
<div class="col-md-6 col-md-offset-3">
<h2>Register</h2>
<form name="form" ng-submit="vm.register()" role="form">
<div class="form-group" ng-class="{ 'has-error': form.fname.$dirty && form.fname.$error.required }">
<label for="username">First name</label>
<input type="text" name="fname" id="fname" class="form-control" ng-model="vm.user.fname" required />
<span ng-show="form.fname.$dirty && form.fname.$error.required" class="help-block">First name is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.lname.$dirty && form.lname.$error.required }">
<label for="username">Last name</label>
<input type="text" name="lname" id="Text1" class="form-control" ng-model="vm.user.lname" required />
<span ng-show="form.lname.$dirty && form.lname.$error.required" class="help-block">Last name is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.username.$dirty && form.username.$error.required }">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" ng-model="vm.user.username" required />
<span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
</div>
<div class="form-group" ng-class="{ 'has-error': form.hashword.$dirty && form.hashword.$error.required }">
<label for="hashword">Password</label>
<input type="hashword" name="hashword" id="hashword" class="form-control" ng-model="vm.user.hashword" required />
<span ng-show="form.hashword.$dirty && form.hashword.$error.required" class="help-block">Password is required</span>
</div>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary">Register</button>
<img ng-if="vm.dataLoading" src="data:image/gif;base64,..." />
Cancel
</div>
</form>
</div>
</div>
Register controller/function
(function () {
'use strict';
angular
.module('app')
.controller('RegisterController', RegisterController);
RegisterController.$inject = ['UserService', '$location', '$rootScope', 'FlashService'];
function RegisterController(UserService, $location, $rootScope, FlashService) {
var vm = this;
vm.register = register;
function register() {
vm.dataLoading = true;
UserService.Create(vm.user)
.then(function (response) {
if (response.success) {
FlashService.Success('Registration successful', true);
$location.path('/login');
} else {
FlashService.Error(response.message);
vm.dataLoading = false;
}
});
return false;
}
}
})();
How did you assign your controller to the view? Did you use the controller as syntax? For example:
<div ng-controller="RegisterController as vm">your view here </div>
You are assigning the register function to vm but the vm is just a local variable in the controller function so angular is not able to use its functions in view.
Assigning this to local vm variable is a good practice, better than using $scope everywhere, but it's still just a local variable inside the controller function's scope. If you assign your controller to view and rename your controller (<div ng-controller="RegisterController as vm">), then it will work.

How to connect Mailchimp subscribers with Firebase using AngularJS

I have my database with Firebase and now I'm trying to do a newsletter subscription, but I want to save the subscribers in Mailchimp and Firebase.
Mailchimp connection works perfectly, but I don't know how to integrate the Firebase connection in the same js.
This is what I have in the <head> tag
<script type="text/javascript">
angular.module("productLaunch", ["mailchimp"])
</script>
This in the <body> tag
<body ng-app="productLaunch"><section class="container-fluid subscribe" ng-controller="MailchimpSubscriptionCtrl">
<div class="wrapper">
<!-- Let us your email -->
<div class="">
<h2 class="text-center">Subscribe to our news</h2>
<div class="col-lg-4 col-lg-offset-4 mt centered">
<h4 ng-hide="mailchimp.result ==='success'">LET ME KNOW WHEN YOU LAUNCH</h4>
<h4 ng-show="mailchimp.result ==='success'">THANKS FOR SIGNING UP!</h4>
</div>
<form class="form-inline" role="form" ng-hide="mailchimp.result === 'success'">
<input class="hidden" type="hidden" ng-model="mailchimp.username" ng-init="mailchimp.username='stopappweb'">
<input class="hidden" type="hidden" ng-model="mailchimp.dc" ng-init="mailchimp.dc='us12'">
<input class="hidden" type="hidden" ng-model="mailchimp.u" ng-init="mailchimp.u='3eb39be3ad857e60b357fdb5e'">
<input class="hidden" type="hidden" ng-model="mailchimp.id" ng-init="mailchimp.id='520ddfd981'">
<div class="form-group">
<label class="sr-only" for="mailchimp.email">Email address</label>
<input type="email" class="form-control" id="mailchimp.email" placeholder="Enter email" ng-model="mailchimp.email">
</div>
<button type="submit" class="btn btn-info" ng-disabled="MailchimpSubscriptionForm.$invalid" ng-click="addSubscription(mailchimp)" type="submit" value="SIGN UP" disabled="disabled">Submit</button>
<div ng-show="mailchimp.result === 'error'">
<p ng-bind-html="mailchimp.errorMessage" class="error"></p>
</div>
</form>
</div>
</div>
</section>
And this is my JS:
'use strict';
angular.module('mailchimp', ['ng', 'ngResource', 'ngSanitize'])
.controller('MailchimpSubscriptionCtrl', ['$log', '$resource', '$scope',
function ($log, $resource, $scope) {
$scope.myData = new Firebase("https://stopappwebpre.firebaseio.com/subscriptors");
// Handle clicks on the form submission.
$scope.addSubscription = function (mailchimp) {
var actions,
MailChimpSubscription,
params,
url;
$scope.myData.push({mailchimp.email:$scope.mailchimp.email});
// Create a resource for interacting with the MailChimp API
url = 'http://' + mailchimp.username + '.' + mailchimp.dc + '.list-manage.com/subscribe/post-json';
params = {
'EMAIL': mailchimp.email,
'FNAME': mailchimp.fname,
'LNAME': mailchimp.lname,
'c': 'JSON_CALLBACK',
'u': mailchimp.u,
'id': mailchimp.id
};
actions = {
'save': {
method: 'jsonp'
}
};
MailChimpSubscription = $resource(url, params, actions);
// Send subscriber data to MailChimp
MailChimpSubscription.save(
// Successfully sent data to MailChimp.
function (response) {
// Define message containers.
mailchimp.errorMessage = '';
mailchimp.successMessage = '';
// Store the result from MailChimp
mailchimp.result = response.result;
// Mailchimp returned an error.
if (response.result === 'error') {
if (response.msg) {
// Remove error numbers, if any.
var errorMessageParts = response.msg.split(' - ');
if (errorMessageParts.length > 1)
errorMessageParts.shift(); // Remove the error number
mailchimp.errorMessage = errorMessageParts.join(' ');
} else {
mailchimp.errorMessage = 'Sorry! An unknown error occured.';
}
}
// MailChimp returns a success.
else if (response.result === 'success') {
mailchimp.successMessage = response.msg;
}
},
// Error sending data to MailChimp
function (error) {
$log.error('MailChimp Error: %o', error);
}
);
}; }]);
Thank you so much for your help.

$auth.login is not a function

I'm using AngularJS 1.4.6 and Satellizer for oauth.
I'm doing everything as written but always get same error:
angular.js:12450 TypeError: $auth.login is not a function
login.html:
<div class="form-group">
<input type="email" class="form-control underline-input" placeholder="Email" ng-model="user.email" required>
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control underline-input" ng-model="user.password" required>
</div>
<div class="form-group text-left mt-20">
<button type="submit" class="btn btn-greensea b-0 br-2 mr-5" ng-click="login()" ng-disabled='form.$invalid'>Login</button>
<label class="checkbox checkbox-custom checkbox-custom-sm inline-block">
<input type="checkbox"><i></i> Remember me
</label>
<a ui-sref="core.forgotpass" class="pull-right mt-10">Forgot Password?</a>
</div>
</form>
Login controller:
.controller('LoginCtrl', function ($scope, $auth) {
$scope.user = {};
$scope.user.email = 'test#gmail.com';
$scope.user.password = 'test';
$scope.login = function () {
$auth.login($scope.user).then (
function (response) {
console.log(response);
},
function (error) {
console.log(error);
}
)
}
app.js:
.config(['$stateProvider', '$urlRouterProvider', '$authProvider', function($stateProvider, $urlRouterProvider, $authProvider ) {
$authProvider.loginUrl = '/auth/login';
...
I tried different settlements, researched github issues but not found a solution.
Whats my fault? How can I fix it?
I add to controller array option
.controller('LoginCtrl', ['$scope','$auth', function ($scope, $auth) {
$scope.user = {};
$scope.user.email = 'test#gmail.com';
$scope.user.password = 'test';
$scope.login = function () {
$auth.login($scope.user).then (
function (response) {
console.log(response);
},
function (error) {
console.log(error);
}
)
}]

$location error in angularJS

I have a master controller and I would like to set up the login page to take me to "/tables" path if username=admin and password=admin, however I am getting this error everytime I try to login
TypeError: Cannot read property 'path' of undefined
I added $location in the controller and in the login function but nothing changed keep getting same error. If I take $location out I get this error
ReferenceError: $location is not defined
Not sure what to do there. Any help is appreciated. Here is my code
angular
.module('RDash')
.controller('MasterCtrl', ['$scope', '$cookieStore', MasterCtrl]);
function MasterCtrl($scope, $cookieStore, $location) {
/**
* Sidebar Toggle & Cookie Control
*/
var mobileView = 992;
$scope.getWidth = function() {
return window.innerWidth;
};
$scope.login = function($location) {
if($scope.credentials.username !== "admin" && $scope.credentials.password !== "admin") {
alert("you are not the admin");
}
else{
$location.path('/tables');
}
};
}
login.html:
<div ng-controller="MasterCtrl">
<form >
<div class="jumbotron" class="loginForm">
<div class="form-group" id="loginPageInput">
<label for="exampleInputEmail1">User Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Username" ng-model="credentials.username">
</div>
<div class="form-group" id="loginPageInput">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" ng-model="credentials.password">
</div>
<div id="loginPageInput">
<button ng-click="login()" type="submit" class="btn btn-primary btn-lg">Submit</button>
</div>
</form>
<div id="loginPageInput">
<div class="wrap">
<button ng-click="register()" class="btn btn-default" id="lefty" >Register</button>
<p ng-click="forgotpass()" id="clear"><a>Forgot my Password</a></p>
</div>
</div>
</div>
</div>
You missed to inject $location in your dependency array of MasterCtrl
Code
angular
.module('RDash')
.controller('MasterCtrl', ['$scope', '$cookieStore', '$location', MasterCtrl]);
//^^^^^^^^
function MasterCtrl($scope, $cookieStore, $location) {
Also you need to remove $scope.login parameter $location which is killing the service $location variable existance which is inject from the controller.
$scope.login = function ()
You are not passing any $location to login function hence it's undefined and shadows outer $location local variable. Correct code should be:
$scope.login = function () {
if ($scope.credentials.username !== "admin" && $scope.credentials.password !== "admin") {
alert("you are not the admin");
} else {
$location.path('/tables');
}
};

Categories