I am trying to display the username "bacon" whenever the user clicks on the button "home" using a vm(view model) in order to transfer the object user which contains the property userName but I get the following error.
app.js:1 Uncaught SyntaxError: Unexpected token <
index.controller.js:1 Uncaught SyntaxError: Unexpected token <
The project has the following hierarchy:
Here is my index.html located at the parent folder ./app
<!DOCTYPE html>
<html>
<head>
<title>MEAN Stack User Registration and Login Example Application</title>
</head>
<body class="container">
<!-- header -->
<header>
<ul class="nav nav-tabs">
<li ng-class="{active: activeTab === 'home'}"><a ui-sref="home">Home</a></li>
</ul>
<div class="flash-message" ng-if="flash">
<div class="{{'alert alert-' + flash.type}}" ng-bind="flash.message"></div>
</div>
</header>
<!-- main -->
<main ui-view></main>
<!-- footer -->
<footer></footer>
<!-- external scripts -->
<!-- application scripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="app.js"></script>
<script src="home/index.controller.js"></script>
<!--<script src="app-services/user.service.js"></script>
<script src="app-services/flash.service.js"></script>-->
<!-- <script src="account/index.controller.js"></script>-->
</body>
</html>
Here is my app.js located at the parent folder ./app
(function () {
'use strict';
angular
.module('app', ['ui.router'])
.config(config)
.run(run);
function config($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home/index.html',
controller: 'Home.IndexController',
controllerAs: 'vm',
data: { activeTab: 'home' }
})
}
function run($http, $rootScope, $window) {
// add JWT token as default auth header
$http.defaults.headers.common['Authorization'] = 'Bearer ' + $window.jwtToken;
// update active tab on state change
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
$rootScope.activeTab = toState.data.activeTab;
});
}
// manually bootstrap angular after the JWT token is retrieved from the server
$(function () {
// get JWT token from server
$.get('/app/token', function (token) {
window.jwtToken = token;
angular.bootstrap(document, ['app']);
});
});
})();
Here is my index.html located at the folder ./app/home
<h1>Hi {{vm.user.firstName}}!!</h1>
Here is my index.controller.js located at the folder ./app/home
(function () {
'use strict';
angular
.module('app')
.controller('Home.IndexController', Controller);
function Controller() {
var vm = this;
vm.user = null;
initController();
function initController() {
var user;
user.firstName = "bacon";
vm.user = user;
// get current user
//UserService.GetCurrent().then(function (user) {
// vm.user = user;
//});
}
}
})();
Related
I've been working on a project for a class and I am getting The [$injector:nomod] error even after declaring a module.js file. I'm still new to angular, I still went and checked all the other questions that had the same problem as me but non of them answered/worked for my problem. Here is my code, please help.
Error:
Uncaught Error: [$injector:nomod] http://errors.angularjs.org/1.6.5/$injector/nomod?p0=MenuAppX
at angular.min.js:7
at angular.min.js:26
at b (angular.min.js:25)
at Object.module (angular.min.js:26)
at categories.component.js:4
at categories.component.js:12
Uncaught Error: [$injector:nomod] http://errors.angularjs.org/1.6.5/$injector/nomod?p0=MenuAppX
at angular.min.js:7
at angular.min.js:26
at b (angular.min.js:25)
at Object.module (angular.min.js:26)
at items.component.js:4
at items.component.js:12
Uncaught Error: [$injector:nomod] http://errors.angularjs.org/1.6.5/$injector/nomod?p0=MenuAppX
at angular.min.js:7
at angular.min.js:26
at b (angular.min.js:25)
at Object.module (angular.min.js:26)
at routes.js:4
at routes.js:25
Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=MenuAppX&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.5%2F%24injector%2Fnomod%3Fp0%3DMenuAppX%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A26%3A408%0A%20%20%20%20at%20b%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A25%3A439)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A26%3A182%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A42%3A290%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20gb%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A46%3A251)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A22%3A332)
at angular.min.js:7
at angular.min.js:43
at p (angular.min.js:8)
at g (angular.min.js:42)
at gb (angular.min.js:46)
at c (angular.min.js:22)
at Uc (angular.min.js:22)
at xe (angular.min.js:21)
at angular.min.js:333
at HTMLDocument.b (angular.min.js:38)
Index
<!DOCTYPE html>
<html ng-app="MenuAppX">
<head>
<meta charset="utf-8">
<title>Menu App</title>
</head>
<body>
<h1>Welcome to the Chinese Menu Website</h1>
<ui-view></ui-view>
<!-- Libraries -->
<script src="lib/angular.min.js"></script>
<script src="lib/angular-ui-router.min.js"></script>
<!-- Modules -->
<script src="src/MenuApp/menuapp.module.js"></script>
<script src="src/MenuApp/data.module.js"></script>
<!-- 'menuapp' modules artifacts -->
<script src="src/MenuApp/menudata.service.js"></script>
<script src="src/MenuApp/categories.component.js"></script>
<script src="src/MenuApp/items.component.js"></script>
<!-- Routes -->
<script src="src/routes.js"></script>
menuapp module
(function () {
'use strict';
angular.module('MenuAppX', ['data']);
});
data module
(function () {
'use strict';
angular.module('data', ['MenuDataService'])
});
menuapp service
(function () {
'use strict'
angular.module('MenuAppX')
.service('MenuDataService', MenuDataService);
MenuDataService.$inject = ['$http'];
MenuDataService = function($http) {
var service = this;
// var categoryPromise = service.getAllCategory();
// var itemPromise = service.getItemsForCategory();
// get later
service.getAllCategory = function() {
var deferred = $q.defer();
var categoriesResult = $http({
method: "GET",
url: ('https://davids-restaurant.herokuapp.com/categories.json'),
});
deferred.resolve(categoriesResult);
}
service.getItemsForCategory = function(categoryShortName) {
var deferred = $q.defer();
var itemsResult = $http({
method: "GET",
url: (' https://davids-restaurant.herokuapp.com/menu_items.json?category='),
params: {
category: categoryShortName
}
});
deferred.resolve(itemsResult);
}
};
});
categories component
(function () {
'use strict';
angular.module('MenuAppX')
.component('categoriesX', {
templateUrl: 'src/MenuApp/template/categories.template.html',
bindings: {
categoriesR: '<'
}
});
})();
items component
(function () {
'use strict';
angular.module('MenuAppX')
.component('categoriesX', {
templateUrl: 'src/MenuApp/template/categories.template.html',
bindings: {
categoriesR: '<'
}
});
})();
routes
(function () {
'use strict';
angular.module('MenuAppX')
.config(RoutesConfig);
RoutesConfig.$inject = ['$stateProvider', '$urlRouterProvider'];
function RoutesConfig($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'src/MenuApp/template/home.template.html'
})
.state('category', {
url: '/menuCategory',
templateUrl: 'src/MenuApp/template/categories.template.html'
})
.state('items', {
url: '/menuItems',
templateUrl: 'src/MenuApp/template/items.template.html'
})
}
})();
You need to load data module first inorder to load the MenuAppX module because its a dependency, change your order of references as
<script src="lib/angular.min.js"></script>
<script src="lib/angular-ui-router.min.js"></script>
<!-- Modules -->
<script src="src/MenuApp/data.module.js"></script>
<script src="src/MenuApp/menuapp.module.js"></script>
<!-- 'menuapp' modules artifacts -->
<script src="src/MenuApp/menudata.service.js"></script>
<script src="src/MenuApp/categories.component.js"></script>
<script src="src/MenuApp/items.component.js"></script>
<!-- Routes -->
<script src="src/routes.js"></script>
I have developed a small task for Gmail user login and logout using firebase authentication. I've faced an issue on my code Uncaught Error: [$injector:modulerr]
I've added the below libraries:
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
And initialized the firebase config.
index.html
<html ng-app="appName">
<body ng-controller="loginCtrl">
<div id="message">
<button ng-click="googleSignin()">SignIn into App</button>
</div>
<p id="load">Firebase SDK Loading…</p>
</body>
When we click the sign in button it will show Gmail authentication popup after complete authenticate it redirect to the htmlnew.html page
app.js
var app = angular.module("appName", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: 'assests/index.html',
controller: 'loginCtrl'
})
});
app.controller('loginCtrl', function ($scope) {
var provider = new firebase.auth.GoogleAuthProvider();
$scope.googleSignin = function () {
firebase.auth()
.signInWithPopup(provider).then(function (result) {
var token = result.credential.accessToken;
var user = result.user;
console.log(token);
console.log(user);
firebase.auth().onAuthStateChanged(function user() {
if (user) {
window.location = 'htmlnew.html';
}
});
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
});
}
});
app.controller('SecondController', [function ($scope) {
$scope.googleSignout = function () {
firebase.auth().signOut()
.then(function () {
console.log('Signout Succesfull');
}, function (error) {
console.log('Signout Failed');
});
}
}]);
htmlnew.html
<html data-ng-app="appName">
<body ng-controller="SecondController">
<div id="message">
<h1>Welcome</h1>
<button ng-click="googleSignout()">Google Signout</button>
</div>
</body>
Here is the problem
1.) It throws the Uncaught Error: [$injector:modulerr] error while entering into htmlnew.html page.
2.) Signout is not working
You forgot to include fireBase module name in app declaration.
angular.module('appName', ['ngRoute','firebase'])
Refer https://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-angularjs-and-firebase--cms-22391
You missed to inject Firebase as a dependency of your application. In your module definition, add firebase:
var app = angular.module("appName", ["ngRoute", "firebase"]);
Here is a JSFiddle demo using Firebase
I have read many tutorials about creating simple modals using angular bootstrap. However, all of the examples seem to be based in single page apps that do not use route provider or other more complex architectural patterns. What specific changes need to be made to the code in this plnkr to enable a modal service to be called through a controller in an app that uses route provider?
The example in the plnkr link above is an app that has:
1.) a route provider with two routes, / and /public1.
2.) A navigation controller handles the table of contents, and thus sits above any/both routes.
3.) A modalService is injected into the navigation controller.
4.) And index.html contains a div with the table of contents that is managed by the navigation controller. A button inside the navigation div in index.html calls the deleteCustomer() method of the controller, which should then cause a modal to appear. What changes need to be made in order for the modal to appear when the button is clicked?
On my devbox, the FireFox debugger is generating the following compilation error when I try to launch the app:
Error: [$injector:modulerr] Failed to instantiate module hello due to:
[$injector:modulerr] Failed to instantiate module navigation due to:
[$injector:modulerr] Failed to instantiate module modalService due to:
[$injector:nomod] Module 'modalService' 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.
http://errors.angularjs.org/1.5.0/$injector/nomod?p0=modalService
minErr/<#http://localhost:9000/bower_components/angular/angular.js:68:12
module/<#http://localhost:9000/bower_components/angular/angular.js:2015:1
ensure#http://localhost:9000/bower_components/angular/angular.js:1939:38
module#http://localhost:9000/bower_components/angular/angular.js:2013:1
loadModules/<#http://localhost:9000/bower_components/angular/angular.js:4503:22
forEach#http://localhost:9000/bower_components/angular/angular.js:321:11
loadModules#http://localhost:9000/bower_components/angular/angular.js:4
When I download the plnkr as a zip then unzip it and debug in my devbox browser, the FireFox debugger says that it is not able to instantiate the hello module, which is the root of the plnkr app. The plnkr app thus should be able to recreate the problem as soon as we figure out the simple problem of getting the main module for the app to load. (A comment explaining how would be appreciated.).
THE CODE:
Though the complete code is in the plnkr at the link above, I will also copy sections of the code as follows:
index.html is:
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<link data-require="ui-bootstrap#0.13.1" data-semver="0.13.1" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" />
<script data-require="ui-bootstrap#0.13.1" data-semver="0.13.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.1/ui-bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js" data-semver="1.5.0" data-require="angularjs#1.5.0"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="hello" ng-cloak class="ng-cloak">
<!-- start of content section -->
<h1>Hello Plunker!</h1>
<div ng-controller="navigation" class="container">
<ul class="nav nav-pills" role="tablist" >
<li><a class="label label-success" href="/">Home</a></li>
<li><a class="label label-success" href="/public1">public1</a></li>
</ul>
<!-- modal test follows -->
<p><a href class="btn btn-default btn-lg " ng-click="deleteCustomer()">Click to Delete Customer</a></p>
<!-- end of modal test -->
</div>
<div class="container">
<div ng-view=""></div>
</div>
<!-- end of content section -->
<!-- begin local build files -->
<!-- <script src="script.js"></script> -->
<script src="modalService.js"></script>
<script src="home.js"></script>
<script src="public1.js"></script>
<script src="navigation.js"></script>
<!-- end local build files -->
</body>
</html>
script.js is:
'use strict';
/** * Main module of the application. */
angular
.module('hello', [
'ngAnimate',
'ngRoute',
'ngTouch', 'home', 'public1', 'navigation'
])
.config(function ($routeProvider, $httpProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs: 'home'
})
.when('/public1', {
templateUrl : 'public1.html',
controller : 'public1',
controllerAs: 'public1'
})
.otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
})
.run([ function() {
}]);
navigation.js is:
'use strict';
angular
.module('navigation', ['modalService', 'ngRoute'])
.controller('navigation', function($scope, modalService, $route) {
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
$scope.deleteCustomer = function () {
var custName = 'Some Random Person';
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Delete Customer',
headerText: 'Delete ' + custName + '?',
bodyText: 'Are you sure you want to delete this customer?'
};
modalService.showModal({}, modalOptions).then(function (result) {
//some code will go here. But for now can we just
//get the modal to appear and for the cancel button to work?
});
}
});
And modalService.js is:
'use strict';
angular.module('modalService').service('modalService', ['$modal',
function ($modal) {
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl: 'modalContent.html'
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
this.showModal = function (customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
this.show = function (customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function ($scope, $modalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function (result) {
$modalInstance.close(result);
};
$scope.modalOptions.close = function (result) {
$modalInstance.dismiss('cancel');
};
}
}
return $modal.open(tempModalDefaults).result;
};
}]);
see below, happy coding ! :)
In plunker you can set <base href="/" />, you have to script that:
<script>
document.write('<base href="' + document.location + '" />');
</script>
You forgot some script required by ui-bootstrap :
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-route.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-touch.js"></script>
And you forgot to load ui.bootstrap in your module :
angular.module('modalService', ['ui.bootstrap']).service('modalService', ['$modal', function(){...})
http://plnkr.co/edit/4BiF2SlhOZDrFgMzj31z?p=preview
I am trying to set up an angularjs application properly with separate controllers.
Using $routeProvider, I want to configure the routing in order to see different views depending on the URL.
So far it's working, but only with the view depending on the last controller loaded.
Here is the code :
Routes configuration, app.js :
'use strict';
var app = angular.module('BalrogApp', ['ngRoute', 'ui.bootstrap', 'BalrogApp.controllers']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/projectsList.html',
controller : 'projectsController',
controllerAs: 'p'
})
.when('/requests', {
templateUrl: 'views/requestsList.html',
controller : 'requestsController',
controllerAs: 'r'
})
.when('/projects', {
templateUrl: 'views/projectsList.html',
controller : 'projectsController',
controllerAs: 'p'
})
.otherwise({
redirectTo: '/lol'
});
}]);
Controller 1, requestsController.js :
'use strict';
var requestsControllerModule = angular.module('BalrogApp.controllers', ['ngRoute', 'ui.bootstrap']);
requestsControllerModule.controller('requestsController', function($rootScope, $scope, $location, $routeParams) {
this.studentName = "Request data";
this.studentMark = 75;
});
Controller 2, projectsController.js :
'use strict';
var projectsControllerModule = angular.module('BalrogApp.controllers', ['ngRoute', 'ui.bootstrap']);
projectsControllerModule.controller('projectsController', function($rootScope, $scope, $location, $routeParams) {
this.studentName = "Project data";
this.studentMark = 75;
});
Main html page, index.html :
<!doctype html>
<html lang="en" ng-app="BalrogApp">
<head>
<meta charset="UTF-8">
<title>Student Details App</title>
<link rel="stylesheet" href="../node_modules/angular-ui-bootstrap/ui-bootstrap-csp.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
</head>
<body>
Index page :
<ng-view></ng-view>
<!--Required JS Files List :start -->
<script src="../node_modules/angular/angular.js"></script>
<script src="../node_modules/angular/angular-route.js"></script>
<script src="../node_modules/angular-ui-bootstrap/ui-bootstrap-tpls.js"></script>
<script src="controllers/requestsController.js"></script>
<script src="controllers/projectsController.js"></script>
<script src="js/app.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!--Required JS Files List :end -->
</body>
</html>
HTML Requests view :
Request view :
<div class="row-fluid">
<div class="span2">{{r.studentName}} </div>
<div style="display:inline-block; min-height:290px;">
<uib-datepicker ng-model="dt" min-date="minDate" show-weeks="true" class="well well-sm" custom-class="getDayClass(date, mode)"></uib-datepicker>
</div>
</div>
HTML Projects view :
Project view :
<div class="row-fluid">
<div class="span2">{{p.studentName}} </div>
<div style="display:inline-block; min-height:290px;">
<uib-datepicker ng-model="dt" min-date="minDate" show-weeks="true" class="well well-sm" custom-class="getDayClass(date, mode)"></uib-datepicker>
</div>
</div>
So the problem there changed depending on index.html :
<script src="controllers/requestsController.js"></script>
<script src="controllers/projectsController.js"></script>
Will result in a working projects view, but not working requests view. If I include the requests controller after, this will be the opposite.
Also, is there a problem with my ControllerAs syntax ? Since I'm using it from the $routeProvider, it's not working at all.
When you do angular.module('BalrogApp.controllers', ['ngRoute', 'ui.bootstrap']);, it creates a new module. What you really want is to reference an existing module, otherwise you will overwrite it every time you load a controller JavaScript file.
Change you controllers initialization to this:
angular.module('BalrogApp').controller('requestsController', function () {
// ...
});
And
angular.module('BalrogApp').controller('projectsController', function () {
// ...
});
This way, you'll be referencing an existing module and will not overwrite it every time.
In your app.js you have already defined the dependencies of modules and by defining again in the controllers you are overriding it, Fix the module line in your controllers as shown below :
Requests View :
'use strict';
var requestsControllerModule = angular.module('BalrogApp.controllers', []); // Fix This..
requestsControllerModule.controller('requestsController', function($rootScope, $scope, $location, $routeParams) {
this.studentName = "Request data";
this.studentMark = 75;
});
Projects view :
var projectsControllerModule = angular.module('BalrogApp.controllers', []); // Fix this..
projectsControllerModule.controller('projectsController', function($rootScope, $scope, $location, $routeParams) {
this.studentName = "Project data";
this.studentMark = 75;
});
In my angularjs project, I have the following files:
/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- Custom Libraries -->
<script src="lib/Shake.js"></script>
<!-- your app's js -->
<script src="js/services/CloudDatabases.js"></script>
<script src="js/controllers.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
/js/apps.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.StatusBar) {
StatusBar.styleDefault();
}
// Register stopping and starting analytics on app open and close
document.addEventListener("pause", window.analytics.Stop(), false);
document.addEventListener("resume", window.analytics.Start(), false);
// Exit the application if you go offline
document.addEventListener("offline", function(){}, false);
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
....
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
});
/js/services/CloudDatabases.js
angular.module('starter.services')
.service('CloudDatabases', ['$http', function ($http) {
var urlBase = '/api/customers';
this.getDatabases = function () {
console.log('CloudDatabases.getDatabases();');
return 'test getDatabasesResponse';
};
}])
/js/controllers.js
angular.module('starter.controllers', ['CloudDatabases'])
// Login controller
.controller('LoginCtrl', function($scope, $ionicLoading, $http, $ionicPopup, $rootScope, $state, $ionicViewService, CloudDatabases) {
CloudDatabases.getDatabases();
// Form data for the login modal
$scope.loginData = {};
// Try loading the loing data from storage if the user has already logged in
$scope.loginData.username = window.localStorage['username'] || '';
$scope.loginData.password = window.localStorage['password'] || '';
$scope.loginData.uk = window.localStorage['uk'] || false;
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
// Show the loading overlay so the user knows we are busy
$ionicLoading.show({template: 'Loading...'});
// Save the login data to local storage so if the user closes the app they
// don't have to re-enter it
window.localStorage['username'] = $scope.loginData.username;
window.localStorage['password'] = $scope.loginData.password;
window.localStorage['uk'] = $scope.loginData.uk;
// Build login JSON from form
var login_json = JSON.stringify({auth: {passwordCredentials: {username: $scope.loginData.username, password: $scope.loginData.password}}});
// POST the actual authentication request
$http({
method: 'POST',
url: 'https://identity.api.rackspacecloud.com/v2.0/tokens',
data: login_json,
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
// Save the auth token and tenant id for later use
$rootScope.userData = [];
$rootScope.userData.Token = response.data.access.token.id;
$rootScope.userData.Tenant = response.data.access.token.tenant.id;
$rootScope.userData.RawServices = response.data.access.serviceCatalog;
// Use viewservice to hide back button on next page and remove login from nav stack
$ionicViewService.nextViewOptions({
disableBack: true
});
// Track successful logins
window.analytics.trackFeature("Login.Success");
$ionicLoading.hide();
// Navigate to Servers page
$state.go('app.servers');
},
function(response) {
// Track failed logins
window.analytics.trackFeature("Login.Failure");
$ionicLoading.hide();
});
};
})
....
But this throws an error saying that it can't be injected.
Can anyone help with why that might be? It says that starter.services isn't defined
The error is because of your service definition. You are using service definition without dependency array [] as second parameter. This tells angular to treat it as getter method for module starter.services instead of defining the module. Use below code for starter.services to fix this.
angular.module('starter.services', [])
.service('CloudDatabases', ['$http', function ($http) {
var urlBase = '/api/customers';
this.getDatabases = function () {
console.log('CloudDatabases.getDatabases();');
return 'test getDatabasesResponse';
};
}])