Angularjs: ReferenceError: scope is not defined - angularjs

I'm a beginner with Angularjs, and I have some difficulties understanding modules and scopes.
I keep getting the error that the scope is undefined, but I don't get why. First I had my controller linked where I set my route, but since the function inside the controller is called on submit button click I took it away. I've tried putting it back, but that didn't make any difference.
This is my js file:
var myApp = angular.module('myApp', ['ngRoute']);
// routes
myApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'about.html',
controller : 'aboutController'
})
// route for the login page
.when('/login', {
templateUrl : 'login.html'
});
});
myApp.controller('mainController', function($scope) {
$scope.message = 'Beginpagina';
});
myApp.controller('aboutController', function($scope) {
$scope.message = 'Informatie over deze pagina';
});
function loginCtrl($scope, $http){
$scope.doLogin = function() {
$http({
method: 'POST',
url: 'loginController.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
'username': $scope.un,
'password': $scope.pw
},
}).
success(function(data, status) {
$scope.data = data;
if(data == 'FALSE'){
$scope.errorMessage = 'Geen geldige inloggegevens';
} else {
scope.$apply(function() { $location.path("/profile"); });
}
}).
error(function(data, status) {
$scope.data = data || "FALSE";
$scope.errorMessage = 'Something went wrong';
});
};
};
And this is my login-page where I get the error, trying to log in:
<div class="span5" ng-controller="loginCtrl">
<form>
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Gebruikersnaam" ng-model="un"
type="text" autocomplete="off">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" ng-model="pw"
type="password" value="" autocomplete="off">
</div>
<input class="btn btn-lg btn-success btn-block" type="submit"
ng-click="doLogin()" value="Login">
<div>{{errorMessage}}</div>
</fieldset>
</form>
</div>
I don't know if I should post the index-page as well, since the routing for home/about page works fine, so the problem is somewhere making the logincontroller and linking it to my submit button. I have found some similar questions, but I haven't seen anyone mix a new controller with myApp controllers, so I might be doing it completely wrong. I've also read that one html page can only have one module, so I didn't know if I could put the login controller apart. It would be nice to have some more info to be put in the right direction. Thanks in advance!

In loginCtrl, you have used scope instead of $scope
Problem is in line
scope.$apply(function()
Use
$scope.$apply(function()

Related

I want to create a route to automatically redirect users to the home page upon logging in

The below code describe my app.js file.
(function () {
'use strict';
angular
.module('app', ['ngRoute', 'ngCookies'])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
.when('/users/login', {
controller: 'LoginController',
templateUrl: 'login/login.view.html',
controllerAs: 'vm'
})
.when('/register', {
controller: 'RegisterController',
templateUrl: 'register/register.view.html',
controllerAs: 'vm'
})
.otherwise({ redirectTo: '/users/login' });
}
})();
The one below describe my login controller.js file: I wrote this route for logging in registered users to the database and creating tokens once the username and password are correct. What I want now is to create an auto route that will redirect the users to the home page once the password and username is correct.
(function () {
'use strict';
angular
.module('app')
.service('Users1', function($http) {
this.logUser = function(user) {
return $http.post("/users/login", user).
then(function(response) {
return response;
}, function(response) {
alert("Error logging in user.");
});
}
})
// .controller('RegisterController', RegisterController);
.controller("LoginController", function($scope, $location, Users1) {
$scope.back = function() {
$location.path("/users/login");
}
$scope.login = function(user) {
Users1.logUser(user).then(function(doc) {
var userUrl = "/" + doc.data.id;
$location.path(userUrl);
}, function(response) {
alert(response);
});
}
})
})();
Below is the html file for the login controller file:
<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" 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="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.password.$dirty && form.password.$error.required }">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" ng-model="user.password" required />
<span ng-show="form.password.$dirty && form.password.$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" ng-click="login(user)">Login</button>
Register
</div>
</form>
$scope.login = function(user) {
Users1.logUser(user).then(function(
$location.path("/");
}, function(response) {
alert(response);
});
}
If you just want to redirect user to the home page. and if you want the userid as urlParams then you should go with this
.when('/:id', {
controller: 'HomeController',
templateUrl: 'home/home.view.html',
controllerAs: 'vm'
})
and the controller
$scope.login = function(user) {
Users1.logUser(user).then(function(doc) {
var userUrl = "/" + doc.data.id;
$location.path(userUrl);
}, function(response) {
alert(response);
});
}
you can use run method to redirect user to home on landing.
You can check when even ever there is route change and redirect him to right place.
$scope.$on('$routeChangeStart', function (event, next, current) {
//add your logic here. if user next contains next route.
});

AngularJS change location is not working

I'm new in ionic
I'm trying to do a simple switch between two views in a login app:
index.html
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Login App</h1>
</ion-header-bar>
<ion-content>
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Email" ng-model="data.email">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
</div>
<button class="button button-block button-calm" ng-click="postLogin()">Login</button>
</ion-content>
</ion-pane>
logincontroller.js
app.controller('loginCtrl', function ($scope,$http,$location)
{
$scope.data = {};
$scope.postLogin = function ()
{
var data =
{
email: $scope.data.email,
password: $scope.data.password
};
console.log('bonjour');
$http.post("http://localhost/authproject/public/api/auth/login", data)
.then(
function(response){
// success callback
console.log('success');
$location.path('/map');
},
function(response){
// failure callback
console.log('error');
$location.path('/index');
}
);
}
When I click on a button Login the url change but the page doesn't change
Could someone tell me how do I solve this ? Thanks in advance :)
In your app.js add a state for map like this (with your own templateUrl and controller value). Make sure to add $stateProvider in the config(). Also, include ui.router to your dependencies. Something like this:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.directives', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider, $httpProvider, $locationProvider){
$stateProvider
.state('map', {
url: '/map',
templateUrl: 'app/views/map.html',
controller: 'MapController'
});
...
And in your index.html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
Try this
app.controller('loginCtrl', function ($scope,$http,$location,$state) {
$scope.data = {};
$scope.postLogin = function ()
{
var data =
{
email: $scope.data.email,
password: $scope.data.password
};
console.log('bonjour');
$http.post("http://localhost/authproject/public/api/auth/login", data)
.then(
function(response){
// success callback
console.log('success');
$location.path('/map');
},
function(response){
// failure callback
console.log('error');
$state.go('main');
});
})
Add a state in app.js
.config(function($stateProvider,$urlRouterProvider){
.state('main', {
url:'/main',
templateUrl:'templates/main.html',
controller:'yourCtrl'
})
$urlRouterProvider.otherwise('/index');
})
Now make in template folder make a page for named main.html

Angular updating and clearing factory variables

I'm creating a single page app in which a user searches for a term, the result gets saved in a variable, and a new page is routed that displays the result. I have this functionality working, however I want the variable to be cleared when the user returns to the previous page and most importantly when the user logs out. What's the proper way to do this? I want the factory to save things for certain pages that I want, and clear them for certain pages I don't want like "home" or "logout".
Factory:
angular.module('firstApp')
.factory('fact', function () {
var service = {};
var _information = 'Default Info';
service.setInformation = function(info){
_information = info;
}
service.getInformation = function(){
return _information;
}
return service;
});
Controller:
angular.module('firstApp')
.controller('InformationCtrl', function($scope, $http, $location, fact) {
$scope.message = 'Hello';
$scope.result = fact.getInformation();
$scope.sub = function(form) {
console.log($scope.name);
$scope.submitted = true;
$http.get('/wiki', {
params: {
name: $scope.name,
}
}).success(function(result) {
console.log("success!");
$scope.result = result;
fact.setInformation(result);
$location.path('/informationdisplay');
});;
}
});
Routes
angular.module('firstApp')
.config(function ($routeProvider) {
$routeProvider
.when('/information', {
templateUrl: 'app/information/input.html',
controller: 'InformationCtrl',
authenticate : true
})
.when('/informationdisplay', {
templateUrl: 'app/information/results.html',
controller: 'InformationCtrl',
authenticate : true
});
});
input.html
<div class="row">
<div class="col-md-6 col-md-offset-3 text-center">
<p>{{result}}</p>
<form class="form" name="form" ng-submit="sub(form)" novalidate>
<input type="text" name="name" placeholder="Name" class="form-control" ng-model="name">
</br>
<button class="btn btn-success" type="submit" class="btn btn-info">Check</button>
</div>
</div>
results.html
<div ng-include="'components/navbar/navbar.html'"></div>
<div class="row">
<div class="col-sm-4 col-sm-offset-4">
<h2>Information Results</h2>
<p>{{result}}</p>
</div>
</div>
</div>
If you want it to wipe the value when they change routes (which logout should change routes also, I assume), you can watch the $routeChangeStart event and have it wipe the value whenever it occurs. You put that function in the module.run block:
app.run(function ($rootScope, fact) {
$rootScope.$on("$routeChangeStart",function(event, next, current){
fact.setInformation(null);
});
});

Satellizer Http Interceptor

Currently I'm using satellizer library to authenticate using json web token. On the backend, I have tested the api and the authentication and everything is working. By the way Im using Twitter authentication.
While on the frontend, which the angular part,After I have authenticated with twitter and successfully redirect to home page, I couldn't get user's information whenever i go to /profile, it doesnt render the user's information and when I check the network tab on google chrome, angular doesnt even call the /api/me route from the backend.
I believe it has something to do with Http interceptor. The authorization header is set as x-access-token both on frontend and backend.
Here's the code.
app.js
angular.module('MyApp', [ 'ngMessages','ngRoute', 'ui.router','satellizer'])
.config(function($authProvider) {
// Twitter
$authProvider.authHeader = 'x-access-token';
$authProvider.httpInterceptor = true; // Add Authorization header to HTTP request
$authProvider.tokenPrefix = 'twitterAuth'; // Local Storage name prefix
$authProvider.twitter({
url: '/auth/twitter',
type: '1.0',
popupOptions: { width: 495, height: 645 }
});
})
.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/views/home.html'
})
.state('login', {
url: '/login',
templateUrl: 'app/views/login.html',
controller: 'LoginCtrl'
})
.state('profile', {
url: '/profile',
templateUrl: 'app/views/profile.html',
controller: 'ProfileCtrl',
})
.state('logout', {
url: '/logout',
template: null,
controller: 'LogoutCtrl'
})
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
})
the controllers
login.js
angular.module('MyApp')
.controller('LoginCtrl', function($scope, $auth) {
$scope.authenticate = function(provider) {
$auth.authenticate(provider);
};
});
profile.js
angular.module('MyApp')
.controller('ProfileCtrl', function($scope, $auth, Account) {
$scope.getProfile = function() {
Account.getProfile()
.success(function(data) {
$scope.user = data;
})
};
});
services
account.js
angular.module('MyApp')
.factory('Account', function($http) {
return {
getProfile: function() {
return $http.get('/api/me');
}
};
});
Views
profile.html
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Profile</div>
<div class="panel-body">
<form method="post">
<div class="form-group">
<label class="control-label">Profile Picture</label>
<img class="profile-picture" ng-src="{{user.picture || 'http://placehold.it/100x100'}}">
</div>
<div class="form-group">
<label class="control-label"><i class="ion-person"></i> Display Name</label>
<input type="text" class="form-control" ng-model="user.displayName" />
</div>
<div class="form-group">
<label class="control-label"><i class="ion-at"></i> Email Address</label>
<input type="email" class="form-control" ng-model="user.email" />
</div>
</form>
</div>
</div>
</div>
This is where the user's information from twitter authentication should render, on the backend everything is showing when I'm using Chrome postman.
I've been pulling my hair for the past 4 hours, so what did I do wrong over here?
I am missing a call to ProfileCtrl's $scope.getProfile. Try this:
angular.module('MyApp')
.controller('ProfileCtrl', function($scope, $auth, Account) {
Account.getProfile()
.success(function(data) {
$scope.user = data;
});
});

ng-click event is not firing on button click?

i'm creating web application in Angularjs i write code in separate .js file for log in from database
is is execute on page load but not triggering on button click,
my .js code is:
var adminModule = angular.module('angApp', []);
//Defining a Angular Controller
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
Login();
function Login(U_Name, U_PWD) {
debugger;
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name, User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
}).error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
}]);
and my view as what i'm using for binding this using Angularjs here is an issue above code is working on page load but don't work on button click, the code i use is:
<div class="admin-login" ng-controller="AdminCtrl" ng-app="angApp">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
anyone please help me what i miss here so i'm not able to trigger ng-click event on button click
thanks in advance.
Your Login function needs to be on a scope. Right now, its essentially a private function:
$scope.Login = function () {
...
}
assign function to a scope variable.
var adminModule = angular.module('angApp', []);
//Defining a Angular Controller
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.Login = function (U_Name, U_PWD) {
debugger;
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name, User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
}).error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
$scope.Login();
}]);
Edited:
try to use this html code,but i am not sure.it may be that both ng-init and ng-controller are in same div and ng-controller load first after that ng-init :
<div ng-app="angApp">
<div class="admin-login" ng-controller="AdminCtrl" >
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>

Resources