I am currently trying to integrate angular bootstrap calendar https://github.com/mattlewis92/angular-bootstrap-calendar into my ionic app. However, I keep running into this error and it is not rendering
Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.4.3/$injector/modulerr?p0=SimpleRESTIonic&p1=
%2F%2Flocalhost%3A8100%2Flib%2Fionic%2Fjs%2Fionic.bundle.min.js%3A50%3A339)
I've tried following the steps mentioned by installing via bower but I am not sure where bower_components is. Thus, I shifted them to the www/lib directory so that they can be accessed. I included the script tags in my index.html.
<link href="lib/angular-bootstrap-calendar/dist/css/angular
bootstrap-calendar.min.css" rel="stylesheet">
<script src="lib/angular-bootstrap-calendar/dist/js/angular
bootstrap-calendar-tpls.min.js"></script>
I went on to install via npm as well because the error was still there.
The following are the code from my respective files:
app.js
angular.module('SimpleRESTIonic', ['ionic', 'backand','SimpleRESTIonic.controllers', 'SimpleRESTIonic.services','mwl.calendar','ui.bootstrap'])
.config(function (BackandProvider, $stateProvider, $urlRouterProvider, $httpProvider) {
// change here to your appName
BackandProvider.setAppName('ionicstarter');
BackandProvider.setSignUpToken('4ce88904-75c5-412c-8365-df97d9e18a8f');
// token is for anonymous login. see http://docs.backand.com/en/latest/apidocs/security/index.html#anonymous-access
BackandProvider.setAnonymousToken('87c37623-a2d2-42af-93df-addc65c6e9ad');
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tabs',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('tab.dashboard', {
url: '/dashboard',
views: {
'tab-dashboard': {
templateUrl: 'templates/tab-dashboard.html',
controller: 'DashboardCtrl as vm'
}
}
})
.state('tab.login', {
url: '/login',
views: {
'tab-login': {
templateUrl: 'templates/tab-login.html',
controller: 'LoginCtrl as login'
}
}
})
.state('tab.signup', {
url: '/signup',
views: {
'tab-signup': {
templateUrl: 'templates/tab-signup.html',
controller: 'SignUpCtrl as vm'
}
}
}
);
$urlRouterProvider.otherwise('/tabs/dashboard');
$httpProvider.interceptors.push('APIInterceptor');
})
.run(function ($ionicPlatform, $rootScope, $state, LoginService, Backand) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
var isMobile = !(ionic.Platform.platforms[0] == "browser");
Backand.setIsMobile(isMobile);
Backand.setRunSignupAfterErrorInSigninSocial(true);
});
function unauthorized() {
console.log("user is unauthorized, sending to login");
$state.go('tab.login');
}
function signout() {
LoginService.signout();
}
$rootScope.$on('unauthorized', function () {
unauthorized();
});
$rootScope.$on('$stateChangeSuccess', function (event, toState) {
if (toState.name == 'tab.login') {
signout();
}
else if (toState.name != 'tab.login' && Backand.getToken() === undefined) {
unauthorized();
}
});
})
controller.js
angular.module('SimpleRESTIonic.controllers', ['angular-bootstrap-calendar',
'angular-ui-bootstrap'])
.controller('calenderController', function($scope, $rootScope){
$scope.calendarView = 'week';
$scope.calendarDay = new Date();
$scope.tester = 'Is the Controller connecting';
$scope.events = [
{
title: 'My event title', // The title of the event
type: 'info',
startsAt: new Date(2013,5,1,1),
endsAt: new Date(2014,8,26,15),
editable: false,
deletable: false,
incrementsBadgeTotal: true
}
];
})
.controller('LoginCtrl', function (Backand, $state, $rootScope, LoginService) {
var login = this;
function signin() {
LoginService.signin(login.email, login.password)
.then(function () {
onLogin();
}, function (error) {
console.log(error)
})
}
function anonymousLogin() {
LoginService.anonymousLogin();
onLogin();
}
function onLogin() {
$rootScope.$broadcast('authorized');
$state.go('tab.dashboard');
login.username = Backand.getUsername();
}
function signout() {
LoginService.signout()
.then(function () {
//$state.go('tab.login');
$rootScope.$broadcast('logout');
$state.go($state.current, {}, {reload: true});
})
}
function socialSignIn(provider) {
LoginService.socialSignIn(provider)
.then(onValidLogin, onErrorInLogin);
}
function socialSignUp(provider) {
LoginService.socialSignUp(provider)
.then(onValidLogin, onErrorInLogin);
}
onValidLogin = function(response){
onLogin();
login.username = response.data;
}
onErrorInLogin = function(rejection){
login.error = rejection.data;
$rootScope.$broadcast('logout');
}
login.username = '';
login.error = '';
login.signin = signin;
login.signout = signout;
login.anonymousLogin = anonymousLogin;
login.socialSignup = socialSignUp;
login.socialSignin = socialSignIn;
})
.controller('SignUpCtrl', function (Backand, $state, $rootScope, LoginService) {
var vm = this;
vm.signup = signUp;
function signUp(){
vm.errorMessage = '';
LoginService.signup(vm.firstName, vm.lastName, vm.email, vm.password, vm.again)
.then(function (response) {
// success
onLogin();
}, function (reason) {
if(reason.data.error_description !== undefined){
vm.errorMessage = reason.data.error_description;
}
else{
vm.errorMessage = reason.data;
}
});
}
function onLogin() {
$rootScope.$broadcast('authorized');
$state.go('tab.dashboard');
}
vm.email = '';
vm.password ='';
vm.again = '';
vm.firstName = '';
vm.lastName = '';
vm.errorMessage = '';
})
.controller('DashboardCtrl', function (ItemsModel, $rootScope) {
var vm = this;
function goToBackand() {
window.location = 'http://docs.backand.com';
}
function getAll() {
ItemsModel.all()
.then(function (result) {
vm.data = result.data.data;
});
}
function clearData() {
vm.data = null;
}
function create(object) {
ItemsModel.create(object)
.then(function (result) {
cancelCreate();
getAll();
});
}
function update(object) {
ItemsModel.update(object.id, object)
.then(function (result) {
cancelEditing();
getAll();
});
}
function deleteObject(id) {
ItemsModel.delete(id)
.then(function (result) {
cancelEditing();
getAll();
});
}
function initCreateForm() {
vm.newObject = {name: '', description: ''};
}
function setEdited(object) {
vm.edited = angular.copy(object);
vm.isEditing = true;
}
function isCurrent(id) {
return vm.edited !== null && vm.edited.id === id;
}
function cancelEditing() {
vm.edited = null;
vm.isEditing = false;
}
function cancelCreate() {
initCreateForm();
vm.isCreating = false;
}
vm.objects = [];
vm.edited = null;
vm.isEditing = false;
vm.isCreating = false;
vm.getAll = getAll;
vm.create = create;
vm.update = update;
vm.delete = deleteObject;
vm.setEdited = setEdited;
vm.isCurrent = isCurrent;
vm.cancelEditing = cancelEditing;
vm.cancelCreate = cancelCreate;
vm.goToBackand = goToBackand;
vm.isAuthorized = false;
$rootScope.$on('authorized', function () {
vm.isAuthorized = true;
getAll();
});
$rootScope.$on('logout', function () {
clearData();
});
if (!vm.isAuthorized) {
$rootScope.$broadcast('logout');
}
initCreateForm();
getAll();
});
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.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="lib/angular-bootstrap-calendar/dist/css/angular-bootstrap-calendar.min.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.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<script src="lib/angularbknd-sdk/dist/backand.debug.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="lib/moment/moment.js"></script>
<script src="lib/angular-bootstrap-calendar/dist/js/angular-bootstrap-calendar-tpls.min.js"></script>
</head>
<body ng-app="SimpleRESTIonic">
<ion-nav-bar class="bar-stable">
<ion-nav-back-button>
</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
</body>
</html>
I also included moment.js in the script according to a suggestion on another question. Could anyone point me in the right direction as to what I should do to get it up and running? Thanks for your help!
Can you please put your code in a github repository and provide the link to there. it will be easier to find the problem
Related
I am trying to pre-load data based on ng-controller attributes prior to displaying the html and in turn prior to button click(submit). I am new to angular js and not sure how to accomplish the task.
There will be one question and n number of answer options
May last try is as seen in code but I need to get to the controller other than button click. I need to see the question and possible answers before the html is present.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/angularjs.min.1.7.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular-route.min.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/app.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/vote.js"></script>
<!--<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/Controllers/HomePageVoteController.js"></script>-->
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/vote.js"></script>
<script src="http://home-dev.kmhp.com/global/js/AngularJS/quick-survey/services/route.js"></script>
<script>
// app
var app = angular.module('quickSurveyApp', ["ngRoute"]);
// controller(s)
app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
//app.controller("VoteCtrl", ["$scope", "qa", "$location", function ($scope, qa, $location) {
// app.factory("VoteService", ["$scope", "qa", "$location", function ($scope, qa, $location) {
$scope.activeQuestions = qa.activeQuestions;
$scope.records = qa.records;
$scope.QuestionText = qa[0].QuestionText;
$scope.AnswerText = qa[0].AnswerText;
$scope.Answers = qa[0].Answers;
$scope.error = false;
$scope.AddVote = function () {
$scope.error = !!$scope.answer;
}
}]);
// service(s)
app.factory("VoteService", ["$http", "$q", function ($http, $q) {
res.setHeader('Access-Control-Allow-Origin', '*');
var service = {};
//Gets all data for page.
var questionNumber = 0;
service.pageInit = function () {
var deferred = $q.defer();
$http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
return service;
}]);
// route(s)
app.config(["$routeProvider", function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/api-test-pages/Quick Survey/survey.html",
//controller: "VoteCtrl",
controller: "VoteCtrl",
// it's is good to download the data before displaying the template without the data
// so all we found in resolve is gonna be "resolved" before display the page and running the controller
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
return VoteService.pageInit();
}]
}
}).
otherwise({
redirectTo: '/'
});
}]);
</script>
</head>
<body ng-app="quickSurveyApp">
<div>
<h1>Quick Survey</h1>
<div ng-view></div>
</div>
</body>
</html>
var app = angular.module("quickSurveyApp", ["ng-Route"]);
app.config(["$routeProvider", function ($routeProvider) {
//res.setHeader('Access-Control-Allow-Origin', '*');
$routeProvider
.when("/", {
templateUrl: "/api-test-pages/Quick-Survey/survey.html",
//templateUrl: "/API/quick-survey/api-test-pages/Quick Survey/survey.html",
controller: "VoteCtrl",
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
// return VoteService.pageInit(1);
return VoteService.pageInit();
}]
}
})
.when("/question/:q", {
templateUrl: "templates/survey.tpl",
controller: "VoteCtrl",
resolve: {
qa: ["VoteService", "$route", function (VoteService, $route) {
var questionNumberFromURL = $route.current.params.q;
//return VoteService.pageInit(questionNumberFromURL);
return VoteService.pageInit();
}]
}
})
.when("/thanks", {
templateUrl: "templates/home.tpl",
controller: ["$timeout", "$scope", "$location", function ($timeout, $scope, $location) {
$scope.message = "Thank you !!!";
$timeout(function () {
$location.path("/");
}, 3000);
}]
}).
otherwise({
redirectTo: '/xxxx.html'
});
var app = angular.module('quickSurveyApp', ["ngRoute"]);
function SetCookiesForDebugging() {
var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla= &psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Timothy+Mruk&id=13332&building=0&guest="
document.cookie = thecookie;
}
// sets all scope variables based on associate cookie information.
function SetUser($scope) {
//Set User Information with Cookie data
$scope.IsManager = getCookie("ismanager");
$scope.UserId = getCookie("emplid"); //
$scope.FirstName = getCookie("fname");
$scope.LastName = getCookie("lname");
$scope.EmailAddress = getCookie("email");
$scope.UserName = getCookie("username");
}
// loops through iNSIGHT cookie to retrieve specific value.
// removes all HTML characters.
function getCookie(name) {
var cookiesArray = document.cookie.split("&");
for (var i = 0; i < cookiesArray.length; i++) {
var nameValueArray = cookiesArray[i].split("=");
var cookieName = decodeURI(nameValueArray[0]);
var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
cookieValue = decodeURIComponent(cookieValue);
if (cookieName == name) {
return decodeURI(cookieValue);
}
}
}
app.controller("VoteCtrl", function ($scope, $http) {
SetCookiesForDebugging();
SetUser($scope);
$scope.voteRequest = {
VoteId: null,
VoteDate: null,
UserName: $scope.UserName,
VoterFname: $scope.FirstName,
VoterLname: $scope.LastName,
Id: null,
QuestionId: null,
QuestionText: "",
AnswerText: ""
};
//Gets all data for page.
$scope.pageInit = function () {
res.setHeader('Access-Control-Allow-Origin', '*');
$http({
method: 'GET',
url: '/API/quick-survey/api/Question/GetQuestionsbyZone/0'
//*url: 'http://localhost:51230/api/Question/GetQuestionsByZone/0'
}).then(function (response){
$scope.activeQuestions = response.data;
},function (error){
console.log(error);
});
};
// inserts new request
$scope.insertRequest = function () {
$http.post("/API/quick-survey/api/Vote/AddVote", $scope.voteRequest).then(function (data, status, headers, config) {
alert("success");
}, function (data, status, headers, config) {
console.log("error!");
console.log(data);
});
};
// checks if user already voted for a question
$scope.getUserVoteCount = function () {
// get true or false
$http.get("/API/quick-survey/api/Vote/GetUserVoteCount/866/ijohnson/0").success(function (data, status, headers, config) {
$scope.activeQuestions = data;
}).error(function (data, status, headers, config) {
console.log(status);
});
};
//radio button click on request form
$scope.handleAnswerRadioClick = function (data) {
$scope.voteRequest.QuestionId = data.QuestionId;
$scope.voteRequest.Id = data.Id;
$scope.voteRequest.AnswerText = data.AnswerText;
};
});
var app = angular.module('quickSurveyApp', ["ngRoute"]);
app.controller("VoteCtrl", ["$scope","qa","$location", function ($scope, qa, $location) {
SetCookiesForDebugging();
SetUser($scope);
$scope.voteRequest = {
VoteId: null,
VoteDate: null,
UserName: $scope.UserName,
VoterFname: $scope.FirstName,
VoterLname: $scope.LastName,
Id: null,
QuestionId: null,
QuestionText: "",
AnswerText: ""
};
$scope.activeQuestions = qa.activeQuestions;
//*******
$scope.Answers = qa.records;
$scope.error = false;
$scope.AddVote = function () {
if ($scope.answer == undefined)
$scope.error = true;
else {
$scope.error = false;
if (qa.next)
$location.path("question/" + qa.next)
else
$location.path("thanks");
}
}
//radio button click on request form
$scope.handleAnswerRadioClick = function (data) {
$scope.voteRequest.QuestionId = data.QuestionId;
$scope.voteRequest.Id = data.Id;
$scope.voteRequest.AnswerText = data.AnswerText;
};
function SetCookiesForDebugging() {
var thecookie = "departid=351&jobtitle=Digital+Developer&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday=0&fsla= &psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=2158635597&emplid=08636&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Timothy&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Mruk&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Isaac+Johnson&id=22665&building=0&guest="
document.cookie = thecookie;
}
// sets all scope variables based on associate cookie information.
function SetUser($scope) {
//Set User Information with Cookie data
$scope.IsManager = getCookie("ismanager");
$scope.UserId = getCookie("emplid"); //
$scope.FirstName = getCookie("fname");
$scope.LastName = getCookie("lname");
$scope.EmailAddress = getCookie("email");
$scope.UserName = getCookie("username");
}
// loops through iNSIGHT cookie to retrieve specific value.
// removes all HTML characters.
function getCookie(name) {
var cookiesArray = document.cookie.split("&");
for (var i = 0; i < cookiesArray.length; i++) {
var nameValueArray = cookiesArray[i].split("=");
var cookieName = decodeURI(nameValueArray[0]);
var cookieValue = nameValueArray[1].replace(/\+/g, '%20');
cookieValue = decodeURIComponent(cookieValue);
if (cookieName == name) {
return decodeURI(cookieValue);
}
}
}
}]);
app.factory("VoteService", ["$http", "$q", function ($http, $q) {
var service = {};
var urlBase = "API/quick-survey/api";
$scope.pageInit = function () {
// Get Questions from api
res.setHeader('Access-Control-Allow-Origin', '*');
$http({
method: 'GET',
url: '/API/quick-survey/api/Question/GetQuestionsByZone/0'
}).then(function (response) {
$scope.activeQuestions = response.data;
}, function (error) {
console.log(error);
});
};
//Gets all data for page.
service.pageInit = function () {
var deferred = $q.defer();
//res.setHeader('Access-Control-Allow-Origin', '*');
//$http.get(urlBase + '/Question/GetQuestionsByZone/' + questionNumber).then(function (response) {
// $http.get(urlBase + '/Question/GetQuestionsByZone/' + 0).then(function (response) {
$http.get('/API/quick-survey/api/Question/GetQuestionsByZone/0').then(function (response) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
// inserts new request
service.insertRequest = function (questionNumber) {
var deferred = $q.defer();
$http.post(urlBase + '/Vote/AddVote', $scope.voteRequest).then(function (response, status, headers, config) {
console.log(response.data);
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
// checks if user already voted for a question
service.getUserVoteCount = function (questionNumber) {
var deferred = $q.defer();
// get true or false
$http.get(urlBase + '/Vote/GetUserVoteCount/866/ijohnson/' + questionNumber).success(function (response, status, headers, config) {
deferred.resolve(response.data);
}, function (error) {
console.error(error);
deferred.reject("error");
});
return deferred.promise;
};
return service;
}]);// JavaScript source code
h1>Quick Survey</h1>
<div ng-model="QuestionText">
<!--Question-->
<h2>{{QuestionText}}</h2>
</div>
<!-- <div -->
<div ng-model="AnswerText">
<!--Possible Answers-->
<br ng-repeat-start="a in Answers" />
<input id="button{{a.AnswerText}}" name="selection" value="{{a.AnswerText}}" type="radio" ng-model="$parent.Answer" />
<label for="button{{a.AnswerText}}" ng-repeat-end>{{a.AnswerText}}</label>
</div>
<br />
<br />
<div>
<input id="surveybtn" type="button" value="Vote Now" ng-click="AddVote()" />
</div>
My ionic 1 project currently has firebase authentication which lets the user log in with an email and password and redirects the user to view that can only be accessed when the user is logged in.
I want to load google maps on the logged in view. I have successfully been able to load google maps on another view that does not firebase authentication in its controller but the minute I put the same code in the controller of the logged in view and setup the div with on the logged in view then it does not load up. There have been no errors in console so im not quite sure what is going on.
So code is as followed:
AuthService calls the firebase service
MuserController (Controller of logged in view):
.controller('MuserCtrl', function($scope, $timeout, $stateParams, ionicMaterialInk, ionicMaterialMotion, $state, AuthService, $cordovaGeolocation) {
$scope.$parent.clearFabs();
$timeout(function() {
$scope.$parent.hideHeader();
}, 0);
ionicMaterialInk.displayEffect();
$scope.current_user = {};
var current_user = AuthService.getUser();
//if user is already logged in
if(current_user) {
//If facebook login
if (current_user && current_user.provider == "facebook") {
$scope.current_user.email = current_user.facebook.displayName;
$scope.current_user.image = current_user.facebook.profileImageURL;
}
//If email login
else {
/*Google Map setting*/
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
}, function(error){
console.log("Could not get location");
});
$scope.current_user.email = current_user.password.email;
$scope.current_user.image = current_user.password.profileImageURL;
}
//No user is currently logged in
} else {
$state.go('app.start');
}
//Logout Function
$scope.logout = function(){
AuthService.doLogout();
$state.go('app.start');
};
})
Services.js (Firebase Authentication Service):
angular.module('socialAuth',[])
.service('AuthService', function($q){
var _firebase = new Firebase("https://logfirebase.firebaseio.com/");
// var _firebase = new Firebase("https://geomuse-169214.firebaseio.com");
// var config = {
// apiKey: "AIzaSyBwdvuilAWOU9DttaGPabpKsHIDHJOuF1Q",
// authDomain: "geomuse-169214.firebaseapp.com",
// databaseURL: "https://geomuse-169214.firebaseio.com",
// projectId: "geomuse-169214",
// storageBucket: "geomuse-169214.appspot.com",
// messagingSenderId: "103764525324"
// };
// firebase.initializeApp(config);
// var rootRef = firebase.database().ref();
this.userIsLoggedIn = function(){
var deferred = $q.defer(),
authService = this,
isLoggedIn = (authService.getUser() !== null);
deferred.resolve(isLoggedIn);
return deferred.promise;
};
this.getUser = function(){
return _firebase.getAuth();
};
this.doLogin = function(user){
var deferred = $q.defer();
_firebase.authWithPassword({
email : user.email,
password : user.password
}, function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
this.doFacebookLogin = function(){
var deferred = $q.defer();
_firebase.authWithOAuthPopup("facebook", function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
this.doSignup = function(user){
var deferred = $q.defer(),
authService = this;
_firebase.createUser({
firstname : user.firstname,
lastname : user.lastname,
email : user.email,
password : user.password,
gender : user.gender
}, function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
// After signup we should automatically login the user
authService.doLogin(user)
.then(function(data){
// success
deferred.resolve(data);
},function(err){
// error
deferred.reject(err);
});
}
});
return deferred.promise;
};
this.doLogout = function(){
_firebase.unauth();
};
})
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="lib/ion-md-input/css/ion-md-input.min.css" rel="stylesheet">
<link href="lib/ionic-material/dist/ionic.material.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/geomuse.css" rel="stylesheet">
<link href="http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic-material/dist/ionic.material.min.js"></script>
<script src="lib/ion-md-input/js/ion-md-input.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<!--Googple maps plugin-->
<script src="http://maps.google.com/maps/api/js?key=AIzaSyAq9weEMgdVahLcdbvokguOZDuZ3PVVyig&sensor=true"></script>
<!--Firebase-->
<script src="lib/firebase/firebase.js"></script>
<script src="lib/angularfire/dist/angularfire.min.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
muser.html (Logged in view):
<ion-view view-title="Login" align-title="left">
<ion-content>
<div id="map"></div>
</ion-content>
</ion-view>
app.js
angular.module('starter', ['ionic', 'starter.controllers', 'ionic-material', 'ionMdInput', 'ngCordova', 'firebase', 'socialAuth'])
.run(function($ionicPlatform, $state, AuthService, $rootScope) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
AuthService.userIsLoggedIn().then(function(response)
{
if(response === true)
{
$state.go('app.muser');
}
else
{
$state.go('auth.connect');
}
});
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
// UI Router Authentication Check
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
if (toState.data.authenticate)
{
AuthService.userIsLoggedIn().then(function(response)
{
if(response === false)
{
event.preventDefault();
$state.go('auth.connect');
}
});
}
});
})
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
// Turn off caching for demo simplicity's sake
$ionicConfigProvider.views.maxCache(0);
/*
// Turn off back button text
$ionicConfigProvider.backButton.previousTitleText(false);
*/
$stateProvider.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.activity', {
url: '/activity',
views: {
'menuContent': {
templateUrl: 'templates/activity.html',
controller: 'ActivityCtrl'
},
'fabContent': {
template: '<button id="fab-activity" class="button button-fab button-fab-top-right expanded button-energized-900 flap"><i class="icon ion-paper-airplane"></i></button>',
controller: function ($timeout) {
$timeout(function () {
document.getElementById('fab-activity').classList.toggle('on');
}, 200);
}
}
}
})
.state('app.register', {
url: '/register',
views: {
'menuContent': {
templateUrl: 'templates/register.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.register-email', {
url: '/register-email',
views: {
'menuContent': {
templateUrl: 'templates/register-email.html',
controller: 'SignUpCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.login', {
url: '/login',
views: {
'menuContent': {
templateUrl: 'templates/login.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.forget-password', {
url: '/forget-password',
views: {
'menuContent': {
templateUrl: 'templates/forget-password.html',
controller: 'ForgetPasswordCtrl'
},
'fabContent': {
template: ''
}
}
})
.state('app.signup', {
url: '/signup',
views: {
'menuContent': {
templateUrl: 'templates/auth/sign-up.html',
controller: 'SignUpCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.connect', {
url: '/connect',
views: {
'menuContent': {
templateUrl: 'templates/auth/connect.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.muser', {
url: '/muser',
views: {
'menuContent': {
templateUrl: 'templates/app/muser.html',
controller: 'MuserCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/start');
});
Help would be greatly appreciated
I have a sails, node-js application in angular-js and I decided to make some tests for it, especifycally in the backend part, for which I am using Jasmine and ngMockE2E tools, because I want to test it with some real server side data.
Here is a part of the code I want to test:
app.controller('IdentificationCtrl', function($scope, $rootScope, ... , ajax) {
_initController = function() {
$scope.loginData = {};
};
$scope.doLogin = function(form) {
if (form.$valid) {
ajax.sendApiRequest($scope.loginData, "POST", "session/login").then(
function(response) {
//$state.go('app.dashboard');
window.localStorage.setItem("sesion", JSON.stringify(response.data));
$rootScope.userTest = response.data;
},
(function(error) {
console.log("error")
})
);
}
};
_initController();
});
Here is my service.js file, in which I provide the ajax service:
angular.module('common.services', [])
.service('ajax', function($http, $rootScope) {
if (window.location.hostname == "localhost") {
var URL = "http://localhost:1349/";
} else {
var URL = "http://TheRealURL/";
}
this.sendApiRequest = function(data, type, method) {
$rootScope.$broadcast('loading:show')
if (method == "session/login" || method == "session/signup") {
var authorization = "";
} else {
var authorization = JSON.parse(window.localStorage["sesion"]).id;
}
data_ajax = {
url: URL + method,
method: type,
headers: {
'Content-Type': 'text/plain',
'authorization': authorization
}
}
if (type === "GET" || type != "delete") {
data_ajax.params = data;
} else {
data_ajax.data = data;
}
if (window.localStorage['admin-language']) {
data_ajax.headers['accept-language'] = window.localStorage['admin-language'];
} else {
data_ajax.headers['accept-language'] = window.navigator.language.toUpperCase();
}
//The test arrives here perfectly
return $http(data_ajax).success(function(data, status, headers, config) {
//But does not enter here
return data;
$rootScope.$broadcast('loading:hide')
}).error(function(data, status, headers, config) {
//Nor here
return data;
$rootScope.$broadcast('loading:hide')
});
//And finally achieves this point, but without making the http call
}
})
Here is the html where I load Jasmine, ngMocks and the test file:
...
<!-- Testing files -->
<link rel="stylesheet" type="text/css" href="lib/jasmine-core/jasmine.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script>
<script type="text/javascript" src="lib/angular-mocks/angular-mocks.js"></script>
<script src="js/TestBackend.js"></script>
...
And here is the above referenced testBackend.js file, in which I intend to make the tests:
describe('FirstCycleController', function() {
beforeEach(module('myApp'));
beforeEach(module('ngMockE2E'));
var $controller;
var $rootScope;
var $httpBackend;
beforeEach(inject(function(_$controller_, _$rootScope_, _$httpBackend_) {
$controller = _$controller_;
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
}));
describe('User login', function() {
it('verifys that a user is correctly logged.', inject(function() {
var $identificationScope = {};
var identificationController = $controller('IdentificationCtrl', { $scope: $identificationScope });
var form = {
$valid: true
}
$identificationScope.loginData = {
email: 'user#test.com',
password: 'usertest'
};
$rootScope.userTest = null;
//pass through everything
$httpBackend.whenGET(/^\w+.*/).passThrough();
$httpBackend.whenPOST(/^\w+.*/).passThrough();
//call the login function simulating a login
$identificationScope.doLogin({ $valid: true });
setTimeout(function() {
expect($rootScope.userTest).not.toBe(null);
}, 150);
}));
});
});
The problem is that when running the testBackend.js test file, it doesn't make any http call. It seems that passThrough() function isn't doing his job correctly.
I faced and corrected the issue of not having defined the passThrough() function, which was because I didn't load the ngMockE2E module(instead of ngMock). But this time Jasmine is working fine and the error is simply that the spec is false:
Error: Expected null not to be null.
Apologies if this issue is already resolved, I couldn't find the solution anywhere.
There is detailed discussion around this on angular github issue
I am having a problem with ngResource. When i add it as a dependencie my app displays blank page. I dont use ngResource for now all i do is declare it as a dependencie. And i have added the script needed for ngResource in my html file. please help
my angular controller looks like this :
var app = angular.module('myApp', ['ngResource']);
app.controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
}]);
app.controller('logoutController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
$scope.gotoregister = function () {
$location.path('/register');
};
}]);
app.controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
My main html file looks like this :
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>MEAN Auth</title>
<!-- styles -->
<link href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.6/yeti/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div ng-view></div>
</div>
<!-- scripts -->
<script src="//code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular-resource.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular-route.min.js"></script>
<script src="./main.js"></script>
<script src="./services.js"></script>
<script src="./controllers.js"></script>
<script src="./chirpApp.js"></script>
</body>
</html>
Beginning to dive into AngularJS so I went to their website, but got stuck on the wire up a backend portion where Angular uses Firebase. The first issue came from the ordering of dependencies:
angular.module('project', ['ngRoute', 'firebase'])
changed to
angular.module('project', ['firebase', 'ngRoute'])
But now it's telling my that $add, in my $scope.save call, is undefined.
Similar $add undefined questions are here and here, but neither seem to apply.
Note: I'm running node's http-server, so I'm assuming it's not a localhost problem.
Scripts
angular.module('project', ['firebase', 'ngRoute'])
.value('fbURL', 'https://unique-url-yay.firebaseio.com/')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebase, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebase, fbRef, fbAuth) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
if (snapshot.val() === null) {
$projects.$set(window.projectsArray);
}
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
return deferred.promise;
});
};
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html',
resolve: {
projects: function (Projects) {
return Projects.fetch();
}
}
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.html'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, projects) {
$scope.projects = projects;
})
.controller('CreateCtrl', function($scope, $location, Projects) {
$scope.save = function() {
Projects.projects.$add($scope.project).then(function(data) {
$location.path('/');
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, Projects) {
var projectId = $routeParams.projectId,
projectIndex;
$scope.projects = Projects.projects;
projectIndex = $scope.projects.$indexFor(projectId);
$scope.project = $scope.projects[projectIndex];
$scope.destroy = function() {
$scope.projects.$remove($scope.project).then(function(data) {
$location.path('/');
});
};
$scope.save = function() {
$scope.projects.$save($scope.project).then(function(data) {
$location.path('/');
});
};
});
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js">
</script>
<script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="scripts.js" type="text/javascript"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="padding:20px;">
<div ng-app="project" class="ng-scope"></div>
<div ng-view></div>
</body>
</html>
Alright, a few things are going on here:
Suggestions
AngularFire was updated to 1.1.1 and $firebase is now deprecated. Use $firebaseObject and $firebaseArray instead.
There is no need to do all that stuff in your Projects service and return a promise. $firebaseObject and $firebaseArray return promises.
Example
Check out this PLNKR I made showing a working version of what you're trying to accomplish.
It's tied to one of my public Firebase instances.
You can create a new piece of data and see it on the home page.
JavaScript:
(function(angular) {
angular.module('project', ['firebase', 'ngRoute'])
.value('fbURL', 'https://sb-plnkr.firebaseio.com/so:28942661')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebaseArray, fbRef) {
this.sync = $firebaseArray(fbRef);
this.sync.$loaded().then(function(data) {
var projects = data;
});
return this.sync;
})
.controller('ListCtrl', function($scope, $location, Projects) {
Projects.$loaded().then(function(data){
$scope.projects = data;
});
})
.controller('CreateCtrl', function($scope, $location, Projects) {
console.log("CreateCtrl");
$scope.save = function() {
console.debug("Adding");
if ($scope.project && $scope.project.content !== '') {
Projects.$add($scope.project).then(function(ref) {
console.log("Added ref",ref);
$location.path('/');
}).catch(function(errorObject){
console.error(errorObject);
});
} else {
alert("You have to enter something.");
}
};
})
.controller('EditCtrl',function($scope, $location, $routeParams, Projects) {
var projectId = $routeParams.projectId,
projectIndex;
$scope.init = function(){
Projects.$loaded().then(function(data) {
$scope.projects = data;
console.info("EditCtrl - Projects.$loaded():",data);
projectIndex = $scope.projects.$indexFor(projectId);
$scope.project = $scope.projects[projectIndex];
});
}
$scope.destroy = function() {
$scope.projects.$remove($scope.project).then(function(data) {
$location.path('/');
});
};
$scope.save = function() {
$scope.projects.$save($scope.project).then(function(data) {
$location.path('/');
});
};
})
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.html'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'create.html'
})
.otherwise({
redirectTo:'/'
});
$locationProvider.html5Mode(true);
});
})(window.angular);
HTML:
(index.html)
<body style="padding:20px;">
<div ng-app="project" ng-controller="EditCtrl">
New
<div ng-view></div>
</div>
</body>
(create.html)
<h2>Create</h2>
<button ng-click="save()">Save</button>
(list.html)
<h2>List</h2>
<div ng-repeat="(key,data) in projects">
<span>$scope.projects[<span ng-bind="key"></span>].content : </span>
<span ng-bind="data.content"></span>
</div>
<h2>Object Debug</h2>
<pre ng-bind="projects | json"></pre>
Hope that helps!