$injector:modulerr : authentication in AngularJS applications - javascript

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

Related

Get new name to show in angular scope

I have a simple angular controller to post a new name and display the name on the page.
The problem is I cant see the name and the rest of the details to show in the scope ....
Any idea how to fix this and why its not working ?
HTML
<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
<meta charset="UTF-8">
<title>Angular Base64 Upload Demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/adonespitogo/angular-base64-upload/master/src/angular-base64-upload.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div ng-controller="UpLoadImage">
<div ng-repeat="step in stepsModel">
<img class="thumb" ng-src="{{step}}"/>
</div>
<label for="file">Select File</label>
<input type='file' name='file' base-sixty-four-input required onload='onLoad' maxsize='600'
accept='image/*' ng-model-instant onchange='angular.element(this).scope().imageUpload(this)'/>
</div>
<div ng-controller="PostData">
{{items.c_name}}
<form ng-submit="sendPost()">
<input ng-model="newName"/>
<button type="submit">Send Data</button>
</form>
</div>
</body>
</html>
App.js
angular.module('myApp', ['naif.base64'])
.controller('UpLoadImage', function ($scope, $http, $window, $rootScope) {
$scope.imageUpload = function (element) {
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(element.files[0]);
};
$scope.imageIsLoaded = function (e) {
$scope.$apply(function () {
$scope.stepsModel.push(e.target.result);
});
$scope.onLoad = function (e, reader, file, fileList, fileOjects, fileObj) {
alert('image uploaded');
};
};
$scope.stepsModel = [];
})
.controller('PostData', function ($scope, $http) {
$scope.items = {
c_name: "Campaign name here",
max_slots: 5,
slots: [
{
slot_id: 1,
base_image: "base 64 image"
}
]
};
$scope.newName = "Enter name";
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
c_name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.items = data;
})
}
});
You missed ng-model property in base-sixty-four-input directive input:
angular.module('myApp', ['naif.base64'])
.controller('UpLoadImage', function ($scope, $http, $window, $rootScope) {
$scope.imageUpload = function (element) {
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(element.files[0]);
};
$scope.imageIsLoaded = function (e) {
$scope.$apply(function () {
$scope.stepsModel.push(e.target.result);
});
$scope.onLoad = function (e, reader, file, fileList, fileOjects, fileObj) {
alert('image uploaded');
};
};
$scope.stepsModel = [];
})
.controller('PostData', function ($scope, $http) {
$scope.items = {
c_name: "Campaign name here",
max_slots: 5,
slots: [
{
slot_id: 1,
base_image: "base 64 image"
}
]
};
$scope.newName = "Enter name";
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
c_name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.items = data;
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
<meta charset="UTF-8">
<title>Angular Base64 Upload Demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/adonespitogo/angular-base64-upload/master/src/angular-base64-upload.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div ng-controller="UpLoadImage">
<div ng-repeat="step in stepsModel">
<img class="thumb" ng-src="{{step}}"/>
</div>
<label for="file">Select File</label>
<input ng-model="file" type='file' name='file' base-sixty-four-input required onload='onLoad' maxsize='600'
accept='image/*' ng-model-instant onchange='angular.element(this).scope().imageUpload(this)'/>
</div>
<div ng-controller="PostData">
{{items.c_name}}
<form ng-submit="sendPost()">
<input ng-model="newName"/>
<button type="submit">Send Data</button>
</form>
</div>
</body>
</html>
Are you sure property c_name exists on the data returned by the $http.post ? . Add a console log to print what you really get. You also have to ensure there is no error by setting an error callback. I also suggest to give a name other than data for the result (res instead of data for example):
var data = {}; // There is already a variable named data here
$http.post("/echo/json/", data).success(function(res, status) {
$scope.items = res;
console.log("$scope.items: ", $scope.items);
}, function() { console.log("There is an error"); })
Add ng-modal to input where you used base-sixty-four-input directive.
Add cdn path of jquery.

angularjs resource error a.push is not a function

I cant save the uploaded file name and format through json value. I'm getting response but I can't save and update in json file sample_data.json. its showing an error:
TypeError: a.push is not a function
Please help me.
Error:
Thanks in advance.
Html
<!DOCTYPE html >
<html ng-app='uploadfiles'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Upload files</title>
</head>
<body ng-controller="uploadCtrl">
<div class="container" >
<form >
<input type="file" ng-file-model="files" multiple model="model" />
<button type="button" ng-click="upload()">Upload</button>
</form>
<p ng-repeat="file in files">
{{file.name}}
</p>
<div id="result">
<p>{{msg}}</p>
</div>
</div>
<script src="lib/angular.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-resource.min.js"></script>
<script src="app/app.js" type="text/javascript"></script>
<script src="app/controller.js" type="text/javascript"></script>
<script src="app/directives.js" type="text/javascript"></script>
</body>
</html>
app.js
var uploadApp = angular.module('uploadfiles',['ngResource', 'myAppServices']);
controller.js
uploadApp.controller('uploadCtrl',['$scope','uploaddata', function($scope, uploaddata, $http) {
$scope.files =[];
$scope.upload=function(){
uploaddata.save($scope.files, function(data) {
$scope.msg ='file saved';
});
};
}]);
var myAppServices = angular.module('myAppServices', ['ngResource']);
myAppServices.factory('uploaddata', ['$resource',
function($resource) {
return $resource('../uploadfiles/temp/sample_data.json', {}, {});
}
]);
Directive.js
uploadApp.directive('ngFileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.ngFileModel);
var isMultiple = attrs.multiple;
var modelSetter = model.assign;
element.bind('change', function () {
var values = [];
angular.forEach(element[0].files, function (item) {
var value = {
// File Name
name: item.name,
//File Size
size: item.size,
type: item.type,
//File URL to view
url: URL.createObjectURL(item),
// File Input Value
_file: item
};
values.push(value);
});
scope.$apply(function () {
if (isMultiple) {
modelSetter(scope, values);
} else {
modelSetter(scope, values[0]);
}
});
});
}
};
}]);
by default, resource expects an object as result, not an array;
try setting the resource option: "isArray: true"

Angularjs Uncaught Error: [$injector:modulerr]

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

AngularJS function in service throwing 'not a function error' after route change?

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?

Making a regular angular app, a modular angular app

Okay so I am trying to learn how to create a modular angular app, but I don't really know how it would look. Based on my code what would I need to do to make it modular? My app is pretty small but I still want to try and get the idea down as for how to create a modular app so that I can just do that from the beginning the next time I create a web app. I didn't include the css as it seems irrelevant for this question. Help would be greatly apprciated.
index.html
<!DOCTYPE html>
<html>
<head>
<header>To do App</header>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>To do App</title>
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"> </script>
<script type='text/javascript' src="//use.edgefonts.net/vast-shadow:n4:all.js"></script>
<script type='text/javascript' src="//use.edgefonts.net/vast-shadow:n4:all;megrim.js"></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script type='text/javascript' src="js/index.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div ng-app="demoApp">
<script type="text/ng-template" id="partials/edit-form.html">
<div ng-show="todo.editMode">
<input ng-model="todo.text" />
<button ng-click="save(todo)">save</button>
</div>
</script>
<div class="todo-wrapper" ng-controller="todoCtrl">
<h2>You have <span class="emphasis">{{getTotalTodos()}}</span> tasks</h2>
<input class="search-input" type="text" ng-model="searchText" placeholder="enter search term" />
<ul>
<li ng-repeat="todo in todos | filter: searchText">
<span>{{todo.text}}: {{todo.date_created}}</span>
<div ng-include="'partials/edit-form.html'"></div>
<button class="clear-btn" ng-click="removeTask(todo)">Remove</button>
<button class="clear-btn" ng-click="editTask(todo)">Edit</button>
</li>
</ul>
<form>
<input class="add-input" placeholder="task name" type="text" ng-model="text" ng-model-instant />
<button class="add-btn" ng-click="addTask()"><h2>Add</h2></button>
</form>
</div>
</body>
</html>
index.js
angular.module('demoApp', [])
.controller('todoCtrl', TodoCtrl);
function TodoCtrl($scope) {
$scope.todos = [{
id: 1,
text: 'Mow the lawn',
selected: false
}, {
id: 2,
text: 'Wash the car',
selected: false
}];
$scope.id = $scope.todos.length + 1; //later create an uuid
$scope.getTotalTodos = function () {
return $scope.todos.length;
};
$scope.addTask = function () {
$scope.todos.push({
editMode: false,
text: $scope.text,
id: $scope.id,
date_created: Date.now,
selected: false
});
$scope.text = '';
$scope.id = '';
};
$scope.removeTask = function (todo) {
/*$scope.todos = _.filter($scope.todos, function (todo) {
return !todo.selected;
});*/
$scope.todos.pop(todo);
//update server now with ngResource...
};
$scope.showDetails = function (task_id) {
var found = $filter('filter')($scope.todos, {
id: task_id
}, true);
if (found.length) {
$scope.selected = JSON.stringify(found[0]);
} else {
$scope.selected = 'Not found';
}
}
$scope.editTask = function(todo) {
todo.editMode = true;
console.log(todo);
};
$scope.save = function(todo) {
todo.editMode = false;
// update data at server now too. $scope.todos is up-to-date
}
$scope.updateTask = function (task_id) {
// search $scope.todos for the item to update
var indexOfTask;
for (var i = 0; i < $scope.todos.length; i++) {
if ($scope.todos[i].id === $scope.id) indexOfTask = i;
$scope.todos[i] = todo;
$scope.todos.push();
$scope.text = '';
$scope.id = '';
}
// update the todo
};
}
Essentially just make a new file for every angular whatever (factory, controller, directive, etc.)
I use this syntax
angular.module('myapp.functionName.type', [])
.type('functionName',);
Then in your app.js, in your case index.js
angular.module('myapp', ['myapp.functionName.type', ... ]) ;

Categories

Resources