This issues seems like a very common one. But I have been unsuccessful to find the issue for a long time now. I have distributed the application, controller,service modules into separate js files as below.
app.js
/** Main AngularJS Web Application */
var app = angular.module('ngdemo', [ 'ngdemo.controllers', 'ngdemo.services' ]);
app
.config([
'$routeProvider',
'$httpProvider',
function($routeProvider, $httpProvider) {
$routeProvider.when('/documents', {
templateUrl : 'documents.html',
controller : 'documentListCtrl'
}).when('/documents/:id', {
templateUrl : 'edit_document.html',
controller : 'documentDetailCtrl'
}).when('/document', {
templateUrl : 'create_document.html',
controller : 'documentCreationCtrl'
}).otherwise({
redirectTo : '/home'
});
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
} ]);
and document_controllers.js
var controllers = angular.module('ngdemo.controllers', []);
/* ... */
controllers.controller( 'navigation', ['$rootScope', '$scope', '$http', '$location', '$route', function($rootScope, $scope, $http, $location, $route) {
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback($rootScope.authenticated);
}).error(function() {
$rootScope.authenticated = false;
callback && callback(false);
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded")
$location.path("/documents");
$scope.error = false;
$rootScope.authenticated = true;
} else {
console.log("Login failed")
$location.path("/home");
$scope.error = true;
$rootScope.authenticated = false;
}
})
};
$scope.logout = function() {
$http.post('logout', {}).success(function() {
$rootScope.authenticated = false;
$location.path("/");
}).error(function(data) {
console.log("Logout failed")
$rootScope.authenticated = false;
});
}
}]);
/* ... */
controllers.controller('documentListCtrl', ['$scope', 'DocumentsFactory', 'DocumentFactory', '$location',
function ($scope, DocumentsFactory, DocumentFactory, $location) {
// callback for ng-click 'editDocument':
$scope.editDocument = function (documentId) {
$location.path('/documents/' + documentId);
};
// callback for ng-click 'deleteDocument':
$scope.deleteDocument = function (userId) {
DocumentFactory.delete({ id: userId });
$scope.documents = DocumentsFactory.query();
};
// callback for ng-click 'createDocument':
$scope.createNewDocument = function () {
$location.path('/document');
};
$scope.documents = DocumentsFactory.query();
}]);
/* ... */
controllers.controller('documentDetailCtrl', ['$scope', '$routeParams', 'DocumentFactory', '$location',
function ($scope, $routeParams, DocumentFactory, $location) {
// callback for ng-click 'updateDocument':
$scope.updateDocument = function () {
DocumentFactory.update($scope.document);
$location.path('/documents');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/documents');
};
$scope.document = DocumentFactory.show({id: $routeParams.id});
}]);
/* ... */
controllers.controller('documentCreationCtrl', ['$scope', 'DocumentsFactory', '$location',
function ($scope, DocumentsFactory, $location) {
// callback for ng-click 'createNewUser':
$scope.createNewDocument = function () {
DocumentsFactory.create($scope.document);
$location.path('/documents');
}
}]);
and finally document_services.js
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('DocumentsFactory', function ($resource) {
return $resource('/rest/documents', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
});
services.factory('DocumentFactory', function ($resource) {
return $resource('/rest/documents/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '#id'} },
delete: { method: 'DELETE', params: {id: '#id'} }
})
});
In my index.html file,
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Sample Project</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/jumbotron.css" rel="stylesheet">
</head>
<body ng-app="ngdemo" class="ng-cloak">
<nav class="navbar navbar-inverse navbar-fixed-top">
<!-- ng-controller="navigation" -->
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li ng-class="{active:tab('home')}">Home</li>
<li ng-show="authenticated" ng-class="{active:tab('document')}">Document</li>
</ul>
<form ng-show="!authenticated" ng-submit="login()"
class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" id="username"
name="username" ng-model="credentials.username" />
</div>
<div class="form-group">
<input type="password" class="form-control" id="password"
name="password" ng-model="credentials.password" />
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
<div ng-show="authenticated" ng-submit="login()"
class="navbar-form navbar-right">
<button type="submit" class="btn btn-success" ng-click="logout()">Log
Out</button>
</div>
</div>
</div>
</nav>
<div ng-view class="container"></div>
<script src="js/angular-bootstrap.js" type="text/javascript"></script>
<script src="js/app.js"></script>
<script src="js/document_controllers.js"></script>
<script src="js/document_services.js"></script>
</body>
</html>
In my project I am using wro4j-maven-plugin to generate javaScript files
<groups xmlns="http://www.isdc.ro/wro">
<group name="angular-bootstrap">
<css>webjar:bootstrap/3.2.0/less/bootstrap.less</css>
<css>file:${project.basedir}/src/main/wro/main.less</css>
<js>webjar:jquery/2.1.1/jquery.min.js</js>
<js>webjar:angularjs/1.3.8/angular.min.js</js>
<js>webjar:angularjs/1.3.8/angular-route.min.js</js>
<js>webjar:angularjs/1.3.8/angular-cookies.min.js</js>
</group>
</groups>
So, this generated angular-bootstrapfile is properly referenced in the html file, but still the loading of modules seems to be failing. Any help is immensely appreciated.
Thanks
You probably need to install the route provider and include ngRoute dependancy in your app.js.
Here is the documentation: $routeProvider
And about the installation: ngRoute
Related
I have this bug when I work authentification between angular js and symfony , I have bug in front end (angular js) :
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=angularApp&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.5%2F%24injector%2Fmodulerr%3Fp0%3Drestangular%26p1%3DTypeError%253A%2520Cannot%2520read%2520property%2520'isUndefined'%2520of%2520undefined%250A%2520%2520%2520%2520at%2520Object.Configurer.init%2520(http%253A%252F%252Flocalhost%252Ftestauthenti%252Fnode_modules%252Frestangular%252Fdist%252Frestangular.js%253A42%253A29)%250A%2520%2520%2520%2520at%2520new%2520%253Canonymous%253E%2520(http%253A%252F%252Flocalhost%252Ftestauthenti%252Fnode_modules%252Frestangular%252Fdist%252Frestangular.js%253A812%253A16)%250A%2520%2520%2520%2520at%2520Object.instantiate%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A44%253A458)%250A%2520%2520%2520%2520at%2520c%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A41%253A370)%250A%2520%2520%2520%2520at%2520Object.provider%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A41%253A312)%250A%2520%2520%2520%2520at%2520d%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A237)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A358%250A%2520%2520%2520%2520at%2520p%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A138)%250A%2520%2520%2520%2520at%2520https%253A%252F%252Fcdnjs.cloudflare.com%252Fajax%252Flibs%252Fangular.js%252F1.6.5%252Fangular.min.js%253A42%253A322%0A%20%20%20%20at%20https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A43%3A70%0A%20%20%20%20at%20p%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A42%3A322%0A%20%20%20%20at%20p%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20gb%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A46%3A251)%0A%20%20%20%20at%20c%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.6.5%2Fangular.min.js%3A22%3A332)
and this is link error:
https://docs.angularjs.org/error/$injector/unpr?p0=RestangularProvider%20%3C-%20Restangular%20%3C-%20MainCtrl
code index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="styles/main.css"> -->
</head>
<body ng-app="angularApp">
<div class="container">
<div ng-include="'main.html" ng-controller="MainCtrl"></div>
<div ui-view></div>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
--> <script src="../node_modules/angular/angular.js"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.js"></script>
-->
<script src="../node_modules/restangular/dist/restangular.js"></script>
<script src="../node_modules/lodash/lodash.js"></script>
<script src="app.js"></script>
<script src="main.js"></script>
</body>
</html>
code main.html:
<!—Displays error or success messages-->
<span>{{message}}</span><br><br>
<!—Login/logout form-->
<form ng-show="!isAuthenticated" ng-submit="submit()">
<label>Login Form:</label><br>
<input ng-model="user.username" type="text" name="user" placeholder="Username" disabled="true" />
<input ng-model="user.password" type="password" name="pass" placeholder="Password" disabled="true" />
<input type="submit" value="Login" />
</form>
<div ng-show="isAuthenticated">
<a ng-click="logout()" href="">Logout</a>
</div>
<div ui-view ng-show="isAuthenticated"></div>
<br><br>
<!—Displays contacts list-->
<h1 ng-show="isAuthenticated">Liste des Contacts</h1>
<article ng-repeat="contact in contacts" ng-show="isAuthenticated" id="{{ contact['#id'] }}" class="row marketing">
<h2>{{ contact.nom }}</h2>
<!—Displays contact phones list-->
<h3 ng-repeat="moyenComm in contact.moyensComm">Tél : {{ moyenComm.numero }}</h3>
</article><hr>
<!—Create contact form-->
<form name="createContactForm" ng-submit="createContact(createContactForm)" ng-show="isAuthenticated" class="row marketing">
<h2>Création d'un nouveau contact</h2>
<!—Displays error / success message on creating contact-->
<div ng-show="contactSuccess" class="alert alert-success" role="alert">Contact publié.</div>
<div ng-show="contactErrorTitle" class="alert alert-danger" role="alert">
<b>{{ contactErrorTitle }}</b><br>
{{ contactErrorDescription }}
</div>
<div class="form-group">
<input ng-model="newContact.nom" placeholder="Nom" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!—Phone form-->
<form name="createPhoneForm" ng-submit="createPhone(createPhoneForm)" ng-show="isAuthenticated" class="row marketing">
<h2>Création d'un nouveau téléphone</h2>
<div ng-show="phoneSuccess" class="alert alert-success" role="alert">Téléphone publié.</div>
<div ng-show="phoneErrorTitle" class="alert alert-danger" role="alert">
<b>{{ phoneErrorTitle }}</b><br>
{{ phoneErrorDescription }}
</div>
<div class="form-group">
<input ng-model="newPhone.numero" placeholder="Numéro" class="form-control">
</div>
<div class="form-group">
<label for="contact">Contact</label>
<!—SelectBox de liste de contacts-->
<select ng-model="newPhone.contact" ng-options="contact['#id'] as contact.nom for contact in contacts" id="contact"></select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
code app.js:
'use strict';
var app = angular
.module('angularApp', ['restangular'])
app.config(['RestangularProvider', function (RestangularProvider) {
// URL ENDPOINT TO SET HERE !!!
RestangularProvider.setBaseUrl('http://your_vhost/api');
RestangularProvider.setRestangularFields({
id: '#id'
});
RestangularProvider.setSelfLinkAbsoluteUrl(false);
RestangularProvider.addResponseInterceptor(function (data, operation) {
function populateHref(data) {
if (data['#id']) {
data.href = data['#id'].substring(1);
}
}
populateHref(data);
if ('getList' === operation) {
var collectionResponse = data['hydra:member'];
collectionResponse.metadata = {};
angular.forEach(data, function (value, key) {
if ('hydra:member' !== key) {
collectionResponse.metadata[key] = value;
}
});
angular.forEach(collectionResponse, function (value) {
populateHref(value);
});
return collectionResponse;
}
return data;
});
}])
;
code main.js:
'use strict';
var app = angular
.module('angularApp')
app.controller('MainCtrl', function ($scope, $http, $window, Restangular) {
// fosuser user
$scope.user = {username: 'johndoe', password: 'test'};
// var to display login success or related error
$scope.message = '';
// In my example, we got contacts and phones
var contactApi = Restangular.all('contacts');
var phoneApi = Restangular.all('telephones');
// This function is launched when page is loaded or after login
function loadContacts() {
// get Contacts
contactApi.getList().then(function (contacts) {
$scope.contacts = contacts;
});
// get Phones (throught abstrat CommunicationWays alias moyensComm)
phoneApi.getList().then(function (phone) {
$scope.phone = phone;
});
// some vars set to default values
$scope.newContact = {};
$scope.newPhone = {};
$scope.contactSuccess = false;
$scope.phoneSuccess = false;
$scope.contactErrorTitle = false;
$scope.contactErrorDescription = false;
$scope.phoneErrorTitle = false;
$scope.phoneErrorDescription = false;
// contactForm handling
$scope.createContact = function (form) {
contactApi.post($scope.newContact).then(function () {
// load contacts & phones when a contact is added
loadContacts();
// show success message
$scope.contactSuccess = true;
$scope.contactErrorTitle = false;
$scope.contactErrorDescription = false;
// re-init contact form
$scope.newContact = {};
form.$setPristine();
// manage error handling
}, function (response) {
$scope.contactSuccess = false;
$scope.contactErrorTitle = response.data['hydra:title'];
$scope.contactErrorDescription = response.data['hydra:description'];
});
};
// Exactly same thing as above, but for phones
$scope.createPhone = function (form) {
phoneApi.post($scope.newPhone).then(function () {
loadContacts();
$scope.phoneSuccess = true;
$scope.phoneErrorTitle = false;
$scope.phoneErrorDescription = false;
$scope.newPhone = {};
form.$setPristine();
}, function (response) {
$scope.phoneSuccess = false;
$scope.phoneErrorTitle = response.data['hydra:title'];
$scope.phoneErrorDescription = response.data['hydra:description'];
});
};
}
// if a token exists in sessionStorage, we are authenticated !
if ($window.sessionStorage.token) {
$scope.isAuthenticated = true;
loadContacts();
}
// login form management
$scope.submit = function() {
// login check url to get token
$http({
method: 'POST',
url: 'http://your_vhost/login_check',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $.param($scope.user)
// with success, we store token to sessionStorage
}).success(function(data) {
$window.sessionStorage.token = data.token;
$scope.message = 'Successful Authentication!';
$scope.isAuthenticated = true;
// ... and we load data
loadContacts();
// with error(s), we update message
}).error(function() {
$scope.message = 'Error: Invalid credentials';
delete $window.sessionStorage.token;
$scope.isAuthenticated = false;
});
};
// logout management
$scope.logout = function () {
$scope.message = '';
$scope.isAuthenticated = false;
delete $window.sessionStorage.token;
};
// This factory intercepts every request and put token on headers
})
app.factory('authInterceptor', function($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
if (response.status === 401) {
// if 401 unauthenticated
}
return response || $q.when(response);
}
};
// call the factory ...
})
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
help me please for resolve this bug and thanks advanced
I think isUndefined is a function in underscore.js, which is a dependency of Restangular:
http://underscorejs.org/#isUndefined
Do you have underscore.js included in your assets?
So I am getting this error: "GET http://localhost:8000/blogs/undefined net::ERR_EMPTY_RESPONSE angular.js:12587".
It happens when I go to my main blog page and when I go to a blog category page. Looking at the network tab I get:
1. blog-home.html 200 xhr angular.js 12587 4.6kb 21ms
2. all 200 xhr angular.js 12587 3.0kb 57ms
3. undefined pending xhr angular.js 12587 3.0kb 57ms 0kb
and the same when I go a blog category page. Ultimately they fail and kick the error above.
So before this gets voted down... I have read and tried here on stack:
No luck. Maybe I missed something or typed something wrong. I'm totally dumbfounded and I feel this is clearly above my skill level. So here is a bunch of code...
Server.js
var express = require('express');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var Mailgun = require('mailgun-js');
var path = require('path');
require('colors');
var app = express();
app.use(favicon(path.join(__dirname, 'client/assets/images', '*****')))
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({extended:true}))
app.use(express.static(path.join(__dirname, 'client')));
app.use(express.static("./bower_components"));
//app.all('/*', function(req, res, next) {
// res.sendFile('index.html', { root: 'client'});
//});
require('./server/config/mongoose.js');
var routes = require('./server/config/routes.js');
routes(app);
var api_key = '*********';
var domain = '*********';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: '********',
to: '********',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
app.listen(8000, function () {
console.log("I'm listening...".blue);
})
Index.html
<!DOCTYPE html>
<html lang="en" ng-app="Bridgeman">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<meta name="description" content="">
<meta name="author" content="">
<meta name="revisit-after" content="10 days">
<meta name="googlebot" content="noodp">
<meta name="msnbot" content="noodp">
<meta name="slurp" content="noodp, noydir">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ; connect-src 'self'; img-src * data:; style-src 'self' 'unsafe-inline'; font-src * data:; frame-src https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d44591.890384371676!2d-118.36723983279781!3d33.83006153459027!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2sus!4v1492366398808 ">
<meta content="/assets/images/******_BigBearSnowTrail.jpg" itemprop="image">
<link href="/assests/images/*******.ico" rel="shortcut icon">
<base href="/" />
<title></title>
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/modern-business.css" rel="stylesheet">
<link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="angular/angular.js"></script>
<script type="text/javascript" src="angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="/factories/ContactFactory.js"></script>
<script src="/factories/loginFactory.js"></script>
<script src="/factories/blogFactory.js"></script>
<script src="/controllers/contactController.js"></script>
<script src="/controllers/servicesController.js"></script>
<script src="/controllers/blogController.js"></script>
<script src="/controllers/blogViewController.js"></script>
<script src="/controllers/blogAWSController.js"></script>
<script src="/controllers/loginController.js"></script>
<base target="_blank">
</head>
<body>
<div ng-include='"templates/header.html"'></div>
<div ng-view=""></div>
<div ng-include='"templates/footer.html"'></div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
app.js (As you see I tried to seperate the AWS category into its own controller and both get's fired when that page loaded)
var Bridgeman = angular.module('Bridgeman', ['ngRoute']);
Bridgeman.config(['$routeProvider', '$httpProvider', '$locationProvider', '$qProvider', function($routeProvider, $httpProvider, $locationProvider, $qProvider){
$qProvider.errorOnUnhandledRejections(false);
$httpProvider.interceptors.push(function($q, $location){
return{
'responseError': function(rejection){
if(rejection.status == 401){
$location.url('/');
}
return $q.reject(rejection);
}
}
});
$routeProvider
.when('/', {
templateUrl:'partials/home.html',
}).when('/about', {
templateUrl:'partials/about.html',
}).when('/services', {
templateUrl: 'partials/services.html',
controller: 'servicesController'
}).when('/blog', {
templateUrl: 'partials/blog-home.html',
controller: 'blogViewController'
}).when('/blogAWS', {
templateUrl: 'partials/blog-aws.html',
controller: 'blogAWSController'
}).when('/blogSEO', {
templateUrl: 'partials/blog-SEO.html',
controller: 'blogViewController'
}).when('/blogSecurity', {
templateUrl: 'partials/blog-Security.html',
controller: 'blogViewController'
}).when('/blogBusiness', {
templateUrl: 'partials/blog-Business.html',
controller: 'blogViewController'
}).when('/blogSportsTech', {
templateUrl: 'partials/blog-SportsTech.html',
controller: 'blogViewController'
}).when('/blog-post/:id', {
templateUrl: 'partials/blog-post.html',
controller: 'blogViewController'
}).when('/contact', {
templateUrl: 'partials/contact.html',
controller: 'contactController'
}).when('/login', {
templateUrl:'partials/login.html',
controller: 'loginController'
}).when('/admin', {
templateUrl:'partials/admin.html',
controller: 'blogController'
}).otherwise({
redirectTo:'/'
});
$locationProvider.html5Mode(true);
}])
Bridgeman.run(function($rootScope, $location, $anchorScroll, $routeParams) {
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
$location.hash($routeParams.scrollTo);
$anchorScroll();
});
})
blog-home.html (This is the main blog page which fires off both functions in my blogViewController)
<!-- Page Content -->
<div class="container">
<!-- Page Heading/Breadcrumbs -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Blog Home
<small>My insights just for you</small>
</h1>
<ol class="breadcrumb">
<li>Home
</li>
<li class="active">Blog Home</li>
</ol>
</div>
</div>
<!-- /.row -->
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8">
<div class="blogs" ng-repeat="b in blogs | orderBy:'-createdAt' | filter:searchblogs">
<!-- Blog Post -->
<h2>
<p>{{b.title}}</p>
</h2>
<p class="lead">
by {{b._user.name}} in the {{b.category}} category
</p>
<p><i class="fa fa-clock-o"></i> Posted on {{b.createdAt | date: "MMM. dd, yyyy"}}</p>
<hr>
<p>{{b.snippet}}</p>
<hr>
<p>{{b.content}}</p>
<a class="btn btn-primary" ng-href="/blog-post/{{b._id}}">Read More <i class="fa fa-angle-right"></i></a>
<hr>
</div>
<hr>
</div>
<!-- Blog Sidebar Widgets Column -->
<div class="col-md-4">
<!-- Blog Search Well -->
<div class="well">
<h4>Search my blogs</h4>
<div class="input-group">
<input type="text" class="form-control" ng-model="searchblogs">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-search"></i></button>
</span>
</div>
<!-- /.input-group -->
</div>
<!-- Blog Categories Well -->
<div class="well">
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-6">
<ul class="list-unstyled">
<li>AWS
</li>
<li>SEO
</li>
<li>Security
</li>
<li>Business Tips
</li>
</ul>
</div>
<!-- /.col-lg-6 -->
<div class="col-lg-6">
<ul class="list-unstyled">
<li>Tech in Sports
</li>
<li>Coming Soon
</li>
<li>Coming Soon
</li>
<li>Coming Soon
</li>
</ul>
</div>
<!-- /.col-lg-6 -->
</div>
<!-- /.row -->
</div>
<!-- Side Widget Well -->
<div class="well">
<h4>My Blog</h4>
<p>Here is a collection of my genius (ha!) and tech insights. I'm sure sooner than later I will discuss Formula 1 tech but be assured there will be plenty of SEO and various web development tips/tools/tricks. And lets not forget some general business savviness I've learned over the years.</p>
</div>
</div>
</div>
<!-- /.row -->
blogViewController (where the functions are. Again, I commented out the getOneBlog and the error didn't happen. So what is triggering this fire and before the button is clicked?)
Bridgeman.controller('blogViewController', function($scope, blogFactory, $location, $routeParams){
console.log("in the blog VIEW controller");
$scope.blogs = [];
$scope.one = [];
blogFactory.getAllBlogs(function(output){
$scope.blogs = output;
console.log(output);
})
blogFactory.getOneBlog($routeParams.id, function(output){
$scope.one = output;
console.log(output);
})
});
blogFactory (no issues here that I am aware of)
Bridgeman.factory('blogFactory', function($http){
var factory = {};
factory.submitNewBlog = function(input, callback){
$http.post('/blogs/new', input).then(function(output){
console.log("we just added a new blog");
callback(output.data);
});
}
//factory.submitNewComment = function(input, callback){
// $http.post('/comments/new', input).then(function(output){
// console.log("we just added a new comment");
// callback(output.data);
// });
//}
factory.getAllBlogs = function(callback){
$http.get('/blogs/all').then(function(output){
console.log("we just got all blogs");
callback(output.data);
});
}
factory.getOneBlog = function(blogID, callback){ //factory.getOneBlog = function(blogID, callback)
$http.get('/blogs/' + blogID).then(function (output){ //$http.get('blogs/' + blogID).then(function (output){
console.log(output.data); //callback(output.data);
console.log("we just got one blog");
callback(output.data);
});
}
return factory;
});
routes (a couple of different styles here just tying different formats to solve this)
var users = require('./../controllers/users.js');
var blogs = require('./../controllers/blogs.js');
module.exports = function(app){
app.post('/reg', function(req, res){
users.reg(req, res);
});
app.post('/login', function(req, res){
users.login(req, res);
});
app.get('/blogs/all', function(req, res) {
blogs.getAllBlogs(req, res);
});
app.get('/blogs/:id', blogs.getOneBlog); //app.get('/blogs/:id', blogs.getOneBlog)
app.post('/blogs/new', function(req, res) {
blogs.addBlog(req, res);
});
app.post('/contact', function(req,res){
var api_key = 'key-2451a2b90a87be616ab68b8f7c8f97ea';
var domain = 'sandbox7dedeb0d5d384b6a8ce4f49165204257.mailgun.org';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: 'Website inquiry <postmaster#sandbox7dedeb0d5d384b6a8ce4f49165204257.mailgun.org>',
to: '*************com',
subject: req.body.full_name+" has sent you a message",
html:
req.body.full_name+" ..."+
req.body.phone+" ..."+
req.body.email+" ..."+
req.body.message
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
console.log("working...");
if(!error)
res.send("Your message has been sent");
else
res.send("Uh oh... something went wrong!");
});
});
}
blogs.js server side controller (no issue here... that I am aware of)
var Blog = mongoose.model('Blog');
module.exports = (function() {
return {
getAllBlogs: function(req, res){
Blog.find({}).populate([{path : '_user'}]).exec(function(err, b){
if(err){
console.log("there was an error when getting all blogs".red);
} else {
console.log(b);
console.log("successfully got all blogs".green);
res.json(b);
}
});
},
getOneBlog: function(req, res) {
console.log('Rich band aid');
if (req.params.id !== 'undefined') {
console.log('there was an id', req.params.id);
Blog.findOne({_id: req.params.id}).exec(function(err, b) { //({_id: req.params.id}, function(err,b){})
if(err){
console.log('error is', err);
console.log("there was an error when getting the blog".red);
} else {
console.log(b);
console.log("successfully got the blog".green);
res.json(b);
}
});
}else {
console.log('no id');
}
},
addBlog: function(req, res) {
console.log("===========================".yellow);
console.log(req.body);
console.log("===========================".yellow);
var b = new Blog({category: req.body.category, title: req.body.title, snippet: req.body.snippet, content: req.body.content, _user: req.body._user})
b.save(function(err){
if(err){
console.log("there was an error when saving a blog".red);
} else {
console.log(b);
console.log("successfully saved the above blog".green);
res.redirect('/blogs/all');
}
})
}
}
})();
and the mongoose db (no issue here... that I am aware of)
var mongoose = require('mongoose');
// Create the message schema
var BlogSchema = new mongoose.Schema({
category: {type: String, required: true, minlength: 3, enum:['Security', 'Business', 'SEO', 'AWS', 'Tech in Sports']},
title: {type: String, required: true, minlength: 3},
snippet: {type: String, required: true, minlength: 3},
content: {type: String, required: true, minlength: 3},
_user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
}, {timestamps: true});
mongoose.model('Blog', BlogSchema);
Any help is greatly appreciated. Thanks
PS... and yes I am aware of the CPS error for the frame-src and the font-src when you try to refresh the page. Super annoying.
Was able to figure it out with a friend. Problem solved by wrapping the 2 functions into an 'if' statement. It may not be the proper solution but it works perfectly.
Bridgeman.controller('blogViewController', function($scope, blogFactory, $location, $routeParams){
console.log("in the blog VIEW controller");
$scope.blogs = [];
$scope.one = [];
if ($routeParams.id) {
blogFactory.getOneBlog($routeParams.id, function(output) {
$scope.one = output;
console.log(output);
});
} else {
blogFactory.getAllBlogs(function(output) {
$scope.blogs = output;
console.log(output);
});
}
});
Could you please let me know what is wrong with my code? I get the initial HTML page, but when I click on "Open", nothing happens. Not even the console logs an error, or any other change.
app.js
var app = angular.module('carApp', ['ui.bootstrap']);
ctrl.js
app.controller('carCtrl', function($scope, $http, $uibModal) {
$http.get('jobs.json').success(function(data) {
$scope.data = data;
$scope.open = function() {
var modalContent = $uibModal.open({
templateUrl: 'careersTpl.html',
controller : modalContentCtrl,
resolve: {
items: function() {
return $scope.data;
}
}
})
}
});
});
var modalContentCtrl = function ($scope, $modalInstance, data) {
$scope.data = data;
$scope.selected = {
item: $scope.data.specs
};
};
JSON:
{
"specs":[
{
"job-title":"TITLE",
"job-apply":"applink",
"job-body":"JOB BODY"
}
]
}
HTML:
<div class="car-up">
<script type="text/ng-template" id="careersTpl.html">
<div class="modal-header">
<h3>Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p ng-repeat="item in data">{{item}}</p>
</div>
</script>
<button class="btn" ng-click="open()">Open</button>
</div>
I'm new to AngularJS, but I have linked the app.js and ctrl.js... thanks.
EDIT: after I've placed ng-controller="carCtrl" in the html file, I receive this error:
Error: [$injector:unpr]
http://errors.angularjs.org/1.5.7/$injector/unpr?p0=%24modalInstanceProvider%20%3C-%20%24modalInstance
O/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:6:412
db/n.$injector<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:43:84
d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:40:344
db/V<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:43:144
d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:40:344
e#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:41:78
h/<.invoke#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:41:163
gf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:89:397
resolveSuccess#https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.2.0/ui-bootstrap-tpls.js:4422:34
e/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:130:409
vf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:103
vf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:142:165
vf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:399
Lc[b]https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:274:444
Sf#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:37:31
Rf/d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:36:486
Please find working demo
angular.module('carApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
var app = angular.module('carApp');
app.controller('carCtrl', function($scope, $http, $uibModal) {
//$http.get('jobs.json').success(function(data) {//Uncomment
//$scope.data = data; Uncomment
//Remove below line from code when you are using this in your project
$scope.data = {
"specs": [{
"job-title": "TITLE",
"job-apply": "applink",
"job-body": "JOB BODY"
}]
}
$scope.open = function() {
var modalContent = $uibModal.open({
templateUrl: 'careersTpl.html',
controller: 'ModalInstanceCtrl',
controllerAs: '$ctrl',
resolve: {
items: function() {
return $scope.data;
}
}
})
}
//});//Uncomment
});
app.controller('ModalInstanceCtrl', function($uibModalInstance, items, $scope) {
$scope.data = items;
console.log($scope.data);
$scope.selected = {
item: $scope.data.specs
};
});
<!doctype html>
<html ng-app="carApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.3.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="carCtrl" class="modal-demo">
<script type="text/ng-template" id="careersTpl.html">
<div class="modal-header">
<h3>Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p ng-repeat="(k,v) in data.specs">
<span>Title: {{v["job-title"]}}<br/> </span>
<span>Link: {{v["job-apply"]}}<br/> </span>
<span>Body: {{v["job-body"]}}<br/> </span>
</p>
</div>
</script>
<button class="btn" ng-click="open()">Open</button>
</div>
</body>
</html>
Try defining the controller like this outside,
app.controller('modalContentCtrl ', function($scope, $modalInstance, data) {
$scope.data = data;
$scope.selected = {
item: $scope.data.specs
};
}
I am having hard time to pass this error:
Uncaught Error: [$injector:modulerr]
when I am trying to make an authentication app with AngularJS. I put the code in plunker.
Here are my codes:
1- app.js
"use strict";
(function() {
var app = angular.module('loginApp', ['AuthService', 'Session']);
app.constant('appSettings', {
title:'Authentication Application',
version:'1.0'
});
app.constant('AUTH_EVENTS', {
loginSuccess: 'auth-login-success',
loginFailed: 'auth-login-failed',
logoutSuccess: 'auth-logout-success',
sessionTimeout: 'auth-session-timeout',
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
});
app.constant('USER_ROLES', {
all: '*',
admin: 'admin',
editor: 'editor',
guest: 'guest'
});
app.controller('footerController', function($scope, appSettings){
$scope.appSettings = appSettings;
});
}());
2 - applicationcontroller.js
"use strict";
(function() {
var applicationcontroller = function ($scope, USER_ROLES, AuthService) {
$scope.currentUser = null;
$scope.userRoles = USER_ROLES;
$scope.isAuthorized = AuthService.isAuthorized;
$scope.setCurrentUser = function (user) {
$scope.currentUser = user;
};
};
applicationcontroller.$inject = ['$scope', 'USER_ROLES', 'AuthService'];
angular.module('loginApp')
.controller('applicationcontroller', applicationcontroller);
}());
3- logincontroller.js
"use strict";
(function() {
var logincontroller = function ($scope, $rootScope, AUTH_EVENTS, AuthService) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function(credentials){
AuthService.login(credentials).then(function(user){
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
$scope.setCurrentUser(user);
}, function(error){
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
});
};
};
logincontroller.$inject = ['$scope', '$rootScope', 'AUTH_EVENTS', 'AuthService'];
angular.module('loginApp')
.controller('logincontroller', logincontroller);
}());
4- authservice.js
"use strict";
(function(){
var AuthService = function($http, Session){
var authService = {};
authService.login = function (credentials) {
return $http
.post('/login', credentials)
.then(function (res) {
Session.create(res.data.id, res.data.user.id,
res.data.user.role);
return res.data.user;
});
};
authService.isAuthenticated = function () {
return !!Session.userId;
};
authService.isAuthorized = function (authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (authService.isAuthenticated() &&
authorizedRoles.indexOf(Session.userRole) !== -1);
};
return authService;
};
AuthService.$inject = ['$http', 'Session'];
angular.module('loginApp').factory('AuthService', AuthService);
}());
5- session.js
"use strict";
(function(){
var Session = function(){
this.create = function (sessionId, userId, userRole) {
this.id = sessionId;
this.userId = userId;
this.userRole = userRole;
};
this.destroy = function () {
this.id = null;
this.userId = null;
this.userRole = null;
};
};
angular.module('loginApp').service('Session', Session);
}());
6- index.html
<!DOCTYPE html>
<html data-ng-app="loginApp" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Authentication</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link href="css/main.css" rel="stylesheet">
</head>
<body ng-controller="applicationcontroller">
<div class="container">
<div class="jumbotron">
<form name="loginForm" ng-controller="logincontroller" ng-submit="login(credentials)" novalidate>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" ng-model="credentials.username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" ng-model="credentials.password" class="form-control">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<hr class="color-violet">
<footer class="text-center" data-ng-controller="footerController"> MADE WITH <i class="fa fa-heart color-violet"></i> BY <span class="color-violet">ALAN SABERI</span>. FIND THIS ON <span class="color-violet">GITHUB</span><div>Version: {{appSettings.version}}</div></footer>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="vendor/bootstrap.min.js"></script>
<script src="vendor/angular.min.js"></script>
<script arc="js/services/authservice.js"></script>
<script arc="js/services/session.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/applicationcontroller.js"></script>
<script src="js/controllers/logincontroller.js"></script>
</body>
</html>
First of all you have a typo when referencing your script files
<script arc="js/services/authservice.js"></script>
<script arc="js/services/session.js"></script>
Should be
<script src="js/services/authservice.js"></script>
<script src="js/services/session.js"></script>
Second -> Your AuthService and Session are not new modules, they are being registered in the same loginApp module based on your code. So you don't inject them into your loginApp module.
Change
var app = angular.module('loginApp', ['AuthService', 'Session']);
to this
var app = angular.module('loginApp', []);
Third -> You are loading your service script files before loading your app.js, remember app.js is where you are first defining your loginApp module that you are using to assign your services, so change your script load order to be this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap.min.js"></script>
<script src="angular.min.js"></script>
<script src="app.js"></script>
<script src="session.js"></script>
<script src="authservice.js"></script>
<script src="applicationcontroller.js"></script>
<script src="logincontroller.js"></script>
Here's your plnkr that's forked and working : http://plnkr.co/edit/5BEIsVxwt8sKwr4HA8Eq?p=preview
I am having an issue with AngularJS where a function from one of my services (authService.isLoggedIn()) is throwing 'not a function' exception in my console. But it only happens after a route change occurs (like after logging in), so before a route change has occured the function is successfully called from within my $routeChangeStart event handler, but after a route change has occured, i receive this exception in my console:
TypeError: authService.isLoggedIn is not a function
at app.config.js:13
If I need to post my server side code (NodeJS + Express for API routing), let me know.
Here is my index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="stylesheet.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-route.min.js"></script>
<base href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.9/ngStorage.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
</head>
<body>
<div ng-controller="navCtrl">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">TriviaAttack!</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a ng-click="showLogin()">Login</a></li>
<li><a ng-click="showRegister()">Register</a></li>
</ul>
</div>
</div>
</nav>
<div ng-view></div>
</div>
<script src="./js/ui-bootstrap-custom-tpls-0.14.0.min.js"></script>
<script src="./app/app.js"></script>
<script src="./app/app.routes.js"></script>
<script src="./app/app.config.js"></script>
<script src="./app/services/authInterceptor.js"></script>
<script src="./app/services/auth.js"></script>
<script src="./app/services/authToken.js"></script>
<script src="./app/services/user.js"></script>
<script src="./app/controllers/nav.js"></script>
<script src="./app/controllers/home.js"></script>
<script src="./app/controllers/login.js"></script>
<script src="./app/controllers/landingpage.js"></script>
</body>
</html>
app.js
var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);
console.log('myApp loaded');
app.routes.js
angular.module('myApp')
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: './app/views/landingpage.html',
controller: 'landingpageCtrl'
})
.when('/home', {
templateUrl: './app/views/home.html',
controller: 'homeCtrl'
});
});
console.log('app.route loaded');
app.config.js
angular.module('myApp')
.config(function($locationProvider, $httpProvider) {
//Removes # from urls.
$locationProvider.html5Mode(true);
//Add authentication interceptor to $httpProvider.interceptors array.
$httpProvider.interceptors.push('authInterceptor');
})
.run(function($rootScope, authService, $location) {
$rootScope.$on('$routeChangeStart', function(event) {
authService.isLoggedIn()
.then(function(response) {
console.log(response);
if (response.status == 200) {
$rootScope.user = response.data;
} else {
console.log('User not authenticated/logged in.');
}
});
});
});
services/authInterceptor.js
angular.module('myApp').
service('authInterceptor', function($location, authToken) {
var service = this;
service.request = function(config) {
config.headers.authorization = authToken.getToken();
return config;
}
service.responseError = function(response) {
$location.path('/');
return response;
}
});
services/auth.js
angular.module('myApp')
.service('authService', function($http) {
var service = this;
service.login = function(user, pass) {
return $http.post('/api/login', {username: user, password: pass});
}
service.isLoggedIn = function() {
return $http.get('/api/user');
}
});
controllers/login.js
angular.module('myApp')
.controller('loginCtrl', function($scope, $modalInstance, $location, authService, authToken) {
$scope.msg = '';
$scope.loginData = {
username: '',
password: ''
}
$scope.login = function() {
authService.login($scope.loginData.username, $scope.loginData.password)
.then(function(response) {
if (response.data.success) {
authToken.setToken(response.data.token);
authService.isLoggedIn = true;
$modalInstance.close();
$location.path('/home');
} else {
$scope.msg = response.data.message;
console.log('error logging in');
}
});
$scope.loginData = {};
};
});
In your controllers/login.js
You are setting
authServer.isLoggedIn to true
That is making it a "boolean" right?