Angular app don't show $scope values, not error message - javascript

i'm learning MEAN stack, and trying to build an app based on demoof this course (thinkster.io/mean-stack-tutorial#creating-schemas-with-mongoose).
I checked that's there is on db with curl, it's ok, but angular dont bind them.
--> This is the view (index.ejs) :
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="javascripts/angularApp.js"></script>
</head>
<body ng-app="demo">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Patients : </h1>
</div>
<div ng-repeat="patient in patients">
<a>{{patient.name}} - Nom: {{patient.surname}} - Age: {{patient.old}}</a>
</div>
</script>
</body>
</html>
--> This is my node js code (index.js)
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Patient = mongoose.model('Patient');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET all patients */
router.get('/patients', function(req, res, next){
Patient.find(function(err, patients){
if(err){ return next(err); }
res.json(patients);
});
});
//configure express : retrieve automatically post by id
router.param('patient', function(req, res, next, id){
var query = Patient.findById(id);
query.exec(function(err, patient){
if(err){ return next(err); }
if(!patient){ return next(new Error("Aucun patient dans la base...")); }
req.patient = patient;
return next();
});
});
module.exports = router;
--> And this is my angular code (angularApp.js)
var app = angular.module('flapperNews', ['ui.router']);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
});
$urlRouterProvider.otherwise('home');
}]);
app.factory('posts', ['$http', function($http){
var o = {
posts: []
};
o.getAll = function() {
return $http.get('/posts').success(function(data){
angular.copy(data, o.posts);
});
};
return o;
}]);
app.controller('MainCtrl', [
'$scope',
'posts',
function($scope, posts){
$scope.posts = posts.posts;
}]);

You didn't bind the controller "MainCtrl" in your html

Related

Angular Error [$injector:modulerr] when loading module

[Update] I've found the site works with Microsoft Edge just fine. IE seems to be the only one having issues.
So I've run into an issue where my site fails to load in Internet Explorer and throws this error:
[$injector:modulerr] Failed to instantiate module necs due to:
Error: [$injector:modulerr] Failed to instantiate module necs.LandingModule.controller due to:
Error: [$injector:nomod] Module 'necs.LandingModule.controller' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument
The site loads completely fine in both Firefox and Chrome, but refuses to load in Internet Explorer. I'm not sure what the issue could be as the 'necs.LandingModule.controller' is both spelled correctly and loaded. I've tried removing some of the code within the Controller to see if it would load, hoping that I could find exactly which piece of code IE doesn't like, but I've yet to be successful in doing that.
Let me know if you need more information and I will provide as needed.
CONTROLLER.JS
angular.module('necs.LandingModule.controller', [
'necs.FeaturedItemsModule.directives'])
.controller('LandingController', ['$scope', '$location', '$routeParams', '$window', 'ajaxUtil',
function($scope, $location, $routeParams, $window, ajaxUtil){
$scope.landingProducts = [1,2,3,4,5,6];
$scope.getFeaturedProducts = function() {
ajaxUtil.get('/api/landingProducts', $scope, 'onGetFeaturedProducts');
};
$scope.onGetFeaturedProducts = function(response) {
if (response) {
$scope.landingProducts = response.data;
}
};
$scope.getCatalogMailer = function(id){
if (id == 'link1'){
$window.open("link");
}else if(id == 'link2'){
$location.url('link');
}else if(id =='link3'){
$location.url('link');
}else if(id =='link4'){
$location.url('link');
}else if(id =='link5'){
$location.url('link');
}
};
$scope.getFeaturedProducts();
ga('send', 'pageview', {
'title': 'landing page'
});
}]);
INDEX.HTML
<!DOCTYPE html>
<html lang="en" ng-app="necs">
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0">
<title>NECS</title>
<link rel="icon" type="image/png" href="assets/images/icon.png" sizes="32x32" />
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="/css/app.css">
<link href='https://fonts.googleapis.com/css?family=Oswald:300,400,700' rel='stylesheet' type='text/css'>
<script src="/bower_components/angular/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
<script src="/bower_components/angular-route/angular-route.js"></script>
<script src="/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script src="/bower_components/angular-strap/dist/angular-strap.min.js"></script>
<script src="/bower_components/angular-strap/dist/angular-strap.tpl.min.js"></script>
<script src="/bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="/bower_components/angularUtils-pagination/dirPagination.js"></script>
<script src="/js/app.js"></script>
<script src="/js/controllers.js"></script>
<script src="/js/directives.js"></script>
<script src="/js/services.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-67702514-1', {
'cookieDomain': 'none'
});
</script>
<base href="/" />
</head>
<body data-spy="scroll" data-offset="15">
<div class="container">
<header-directive></header-directive>
<div ng-view >
</div>
</div>
<div class="main-footer">
<div class="container">
<footer-directive></footer-directive>
</div>
</div>
</body>
</html>
LANDING.HTML
<div class="landing row">
<div class="row">
<div class="col-xs-12">
<div class="well">
<custom-order-directive></custom-order-directive>
<featured-items-directive></featured-items-directive>
</div>
</div>
</div>
<div class="row">
<div ng-repeat="item in landingProducts" class="col-sm-12 col-md-4">
<div class="thumbnail main-container">
<div class="image-container">
<!--<img ng-click="onProductClick(item.id)" class="top-sellers" ng-src="{{item.img}}" />-->
<img ng-src="{{item.image}}" />
</div>
<div class="caption text-center landinglinks">
<h3 >{{item.header}}</h3>
<!--<p ng-bind-html="item.text" ng-click="onProductClick(item.link)"></p>-->
<p ng-bind-html="item.text" ng-click="getCatalogMailer(item.link)"></p>
</div>
</div>
</div>
</div>
FRONT APP.JS
angular.module('necs', ['ngRoute',
'necs.LandingModule.controller',
'necs.CustomModeModule.controller',
'necs.CustomOrderModule.controller',
'necs.CustomPdfModule.controller',
'necs.CatalogModule.controller',
'necs.ProductModule.controller',
'necs.HeaderModule.directives',
'necs.FooterModule.directives',
'necs.MenuModule.directives',
'necs.DownloadsModule.controller',
'necs.InformationModule.controller',
'necs.LoginModule.controller',
'necs.AccountModule.controller',
'necs.AdministrationModule.controller',
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'html/landing.html',
controller: 'LandingController'
})
.when('/customMode', {
templateUrl: 'html/customMode.html',
controller: 'CustomModeController'
})
.when('/customOrder', {
templateUrl: 'html/customOrder.html',
controller: 'CustomOrderController'
})
.when('/customPdf', {
templateUrl: 'html/customPdf.html',
controller: 'CustomPdfController'
})
.when('/catalog', {
templateUrl:'html/catalog.html',
controller: 'CatalogController'
})
.when('/catalog/product', {
templateUrl: 'html/product.html',
controller: 'ProductController'
})
.when('/downloads', {
templateUrl: 'html/downloads.html',
controller: 'DownloadsController'
})
.when('/information', {
templateUrl: 'html/information.html',
controller: 'InformationController'
})
.when('/cart', {
templateUrl: 'html/cart.html',
controller: 'CartController'
})
.when('/login', {
templateUrl: 'html/login.html',
controller: 'LoginController'
})
.when('/account', {
templateUrl: 'html/account.html',
controller: 'AccountController'
})
.when('/administration', {
templateUrl: 'html/administration.html',
controller: 'AdministrationController'
})
.otherwise({
redirectTo: '/'
});
}]);
SERVER APP.JS
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var session = require('express-session');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var nodemailer = require('nodemailer');
var exphbs = require('express-handlebars');
var hbs = require('nodemailer-express-handlebars');
var db = require('./db')();
var user = require('./user')();
var fs = require('fs');
var Cookies = require('cookies');
var Product = require('./product');
var Category = require('./category');
var Download = require('./download');
var Codes = require('./codes');
var Specsheet = require('./specsheet');
var app = express();
app.use(express.static(path.resolve(__dirname + '/../front/static')));
app.use(bodyParser.urlencoded({limit: '50mb'}));
app.use(bodyParser.json({limit: '50mb'}));
app.get('/qr/:qrcode', function (req, res) {
var domain = 'domain.com/#/qr/';
var qrcode = req.params.qrcode;
res.redirect(domain+qrcode);
});
//login
app.use(flash());
app.get('/', function(req, res) {
res.sendfile('index.html');
});
// parse application/json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var server = app.listen(80);
var config = {
"USER": "user",
"PASS": "password",
"HOST": "127.0.0.1",
"PORT": "22222",
"DATABASE" : "database"
};
var dbPath = "mongodb://" + config.USER + ":"+ config.PASS + "#"+ config.HOST + ":"+ config.PORT + "/"+ config.DATABASE;
mongoose.connect(dbPath);
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log('connected successfully');
});
//landing products
app.get('/api/landingProducts',function(req,res) {
var landingItems = {
landing1: {
image: "/assets/images/landing1.jpg",
text: "text1",
header: "header1",
link: "link1"
},
landing2: {
image: "/assets/images/landing2.jpg",
text: "text2",
header: "header2",
link: "link2"
},
landing3: {
image: "/assets/images/landing3.jpg",
text: "text3",
header: "header3",
link: "link3"
},
landing4: {
image: "/assets/images/landing4.jpg",
text: "text4",
header: "header4",
link: "link4"
},
landing5: {
image: "/assets/images/landing5.jpg",
text: 'text5',
header: "header5",
link: "link5"
},
landing6: {
image: "/assets/images/landing6.jpg",
text: "text6",
header: "header6",
link: "link5"
}
};
res.send(landingItems);
});
I tested on IE 11:
This is what I am getting: Expected ':' in controllers.js (1551,3)
It looks like you have declared 3 additional variables, but not properly:
$scope.getWidthDropdown = {
warr
};
And there are two others.
You should change that to
$scope.getWidhtDropdown = {
warr: warr
};
I am not sure if that will fix the issue though. Could be a red herring

Angular Routing Causing infinite loop when using parameters in url

I am getting infinite loop when trying to access a parameterized url in angular.
Here is the code.
app.js
var express = require("express");
var cors = require("cors");
var app = express();
app.use(express.static(__dirname));
app.use('/',function(req,res){
res.sendFile("./home.html");
});
app.listen("4467", function() {
console.log("Started listening at port 4467 new");
});
home.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="a02.js"></script>
</head>
<body ng-app="testApp">
Hello Homepage
<div ng-view></div>
</body>
</html>
a02.js
var app = angular.module("testApp", ['ngRoute']);
app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
$routeProvider.when('/test/:a', {
templateUrl: './sum.html',
controller: 'sum'
})
.when("/",{
templateUrl:"./a02.html"
})
.otherwise({
template:"Otherwise"
});
$locationProvider.hashPrefix('');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}]);
app.controller('sum', function($scope, $routeParams) {
console.log("I am controller "+ $routeParams.a);
$scope.a = $routeParams.a;
$scope.b = $routeParams.b;
});
a02.html
Hello there
<hr>
<script> console.log("Getting called again");</script>
Click Me
My requirement is when I click on the Click Me link it should replace the existing ng-view template i.e a02.html to sum.html.
sum.html
<div>
Value of a: {{a}} </br>
Value of b: {{b}}
</div>
But I am getting infinite loop when click on Click Me link.Can someone tell me what I am missing here?

req.flash weird behaviour with Angular ngRoute

Well, I'm building a simple login page using the MEAN stack. I'm using passport to authenticate, connect-flash to flash messages and Angular ngRoute to, well, route. I have the following code:
app.js
var app = angular.module("app", ["ngRoute"]);
app.factory("appFactory", function($http) {
return {
getData: function(path) {
return $http.get(path)
.then(function(response) {
return response.data;
}, function(response) {
console.log("Error...");
});
}
};
});
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "homeCtrl",
resolve: {
getMessage: function(appFactory) {
return appFactory.getData("/api/login");
}
}
})
.otherwise({
redirectTo: "/"
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
//to fix!
app.controller("homeCtrl", function($scope, getMessage) {
$scope.errors = getMessage.errors;
});
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>My Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.min.js"></script>
</head>
<body>
<!-- ngView -->
<div ng-view></div>
<!-- /ngView -->
<script src="/javascript/angular/app.js"></script>
</body>
</html>
home.html
<form action="/" method="post">
<label>E-mail:</label>
<br/>
<input type="email" name="email" />
<br/>
<label>Password:</label>
<br/>
<input type="password" name="password" />
<br/>
<input type="submit" name="submit" value="Log In" />
</form>
<!-- prints error messages (usually, only one) -->
<span ng-repeat="error in errors">{{errors[$index]}}</span>
login.js
var passport = require("passport");
module.exports = function(app) {
app.get("/api/login", function(req, res) {
var info = {
logged: false,
errors: req.flash("error")
};
if (!req.user) {
console.log(info.errors);
} else {
info.logged = true;
}
res.json(info);
});
}
index.js
var passport = require("passport");
var path = require("path");
module.exports = function(app) {
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "../views/index.html"));
});
app.post("/",
passport.authenticate("local-login", {
successRedirect: "/profile",
failureRedirect: "/",
failureFlash: true
}));
}
So, I'm testing wrong logins, expecting req.flash() to reset after a refresh on the homepage, but it takes some refreshs before resetting. As you can see, I've put a console check when the api is called falsely, and the console outputs:
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
['Inexistent username!']
[]
[]
[]
[]
See? It takes some refreshes before cleaning its value. It has nothing to do with my passport authentication strategy nor anything else but the resolve inside the routing. When I attempt to use it without routes (directly on the controller) it works perfectly. Please, help me enlighten my mind on this one and thank you for your time.

TemplateURL provided in angular js routes isn't loading the required file when getting response from node

I am trying to fetch data from mysql using node(routes.js) and wanted the result to be injected in club.html ,file which is dynamically updated in index.html using ng-view. But when i try this scenario i see the node response (i.e json containing results) is directly getting displayed on browser rather than injecting to club.html then displaying
Below are following files:
appRoutes.js --> for routing on angular side
clubCtrl.js --> club controller
clubService.js --> club service to fill data from node
Routes.js --> partial sample of retriving data from database and sending response
club.html --> partial club view file
index.html --> file on which club.html will get dynamically displayed using ng-view.
app.js -> injecting all modules
**appRoutes.js**
angular.module('appRoutes', []).config(['$routeProvider', function($routeProvider) {
$routeProvider
// home page
.when('/', {
templateUrl: 'views/home.html',
controller: 'MainController'
})
// nerds page that will use the NerdController
.when('/club', {
templateUrl: 'views/club.html',
controller: 'ClubController'
});
}]);
**ClubCtrl.js**
angular.module('ClubCtrl', []).controller('ClubController', [ '$http','Club', function($http, Club) {
var club = this;
club.data = {};
Club.getClubData().then(function(response){
club.data = response.data;
});
}]);
**ClubService.js**
angular.module('ClubService', []).factory('Club', ['$http', function($http) {
return {
getClubData : function() {
return $http.get('/club');
}
};
}]);
**Routes.js**
module.exports = function(app) {
app.get('/', function(req, res) {
console.log("routes send get(*)");
res.sendFile(path.resolve('public/index.html')); // load our public/index.html file
});
app.get('/club', function(req, res){
console.log("routes send get /club");
con.query("select * from club_data", function(err, rows,field) {
if (!err)
{
console.log('The solution is: ', rows);
res.json(rows);
}
else
console.log('Error while performing Query. ', err);
});
});
};
**Club.html**
</div>
<div class="row " >
<div class="col-md-3 col-sm-6 image-feature" ng-repeat='dat in main.data'>
<div class="thumbnail">
<img ng-src="images/club/{{dat.imagename}}"alt="">
<div class="caption">
<h3>{{ dat.name }}</h3>
<p>{{dat.desccription}}</p>
<p>{{dat.date}}</p>
<p>
I'm Going!
</p>
</div>
</div>
</div>
**index.html**
<body ng-app="staygala" ng-controller="MainController">
<!-- ANGULAR DYNAMIC CONTENT -->
<div ng-view></div>
</body>
**app.js**
angular.module('staygala', ['ngRoute', 'appRoutes', 'MainCtrl', 'ClubCtrl', 'ClubService']);
I assume you are using same port.
Change your route from /club to /api/club in nodejs side route and call it like return $http.get('/api/club'); in angular service i.e in ClubService.js because when you call your page in the browser with /club. node server catches it and renders the json as response.
so here is the change you have to make :
in Routes.js
module.exports = function(app) {
app.get('/', function(req, res) {
console.log("routes send get(*)");
res.sendFile(path.resolve('public/index.html')); // load our public/index.html file
});
app.get('/api/club', function(req, res){
console.log("routes send get /club");
con.query("select * from club_data", function(err, rows,field) {
if (!err)
{
console.log('The solution is: ', rows);
res.json(rows);
}
else
console.log('Error while performing Query. ', err);
});
});
};
and in ClubService.js
angular.module('ClubService', []).factory('Club', ['$http', function($http) {
return {
getClubData : function() {
return $http.get('/api/club');
}
};
}]);
One more thing you are using main.data in ng-repeat in view club.html but i am not able to see controllerAs in route so you have to add controllerAs in angular club route or change model in controller.

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?

Categories

Resources