I am learning angularjs and i am stuck at one point. I keep getting error
ncaught Error: [$injector:modulerr] Failed to instantiate module ui.bootstrap.demo due to:
Error: [$injector:nomod] Module 'ui.bootstrap.demo' is not available!
Below is my html file
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.3.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.js"></script>
<script src="resources/js/main.js"/>
<script src="resources/js/gsenv.js"/>
<script src="resources/js/CarouselController.js"/>
</head>
However if i dont write the javascripts in separate file it works as exected
<script type="text/javascript">
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope, $http, dataShare) {
$scope.myInterval = 5000;
$scope.noWrapSlides = false;
$scope.active = 0;
var slides = $scope.slides = [];
var currIndex = 0;
$scope.sendEnvName = function(data) {
dataShare.sendEnvNameDetails(data);
}
$scope.addSlide = function (envName) {
slides.push({
text: envName,
id: currIndex++
});
};
$http.get("http://localhost:8080/getEnvList")
.success(function (data) {
for (var i in data) {
$scope.addSlide(data[i].envName);
}
});
});
It works fine this way, not able to understand what could be the issue
main.js
var app = angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap', 'ngTable']);
jsenv.js
app.factory('dataShare',function($rootScope){
var service = {};
service.envName = 'no-env'
service.sendEnvNameDetails = function(data){
console.log(data)
this.envName = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.envName;
};
return service;
});
carousel
app.controller('CarouselDemoCtrl', function ($scope, $http, dataShare) {
$scope.myInterval = 5000;
$scope.noWrapSlides = false;
$scope.active = 0;
var slides = $scope.slides = [];
var currIndex = 0;
$scope.sendEnvName = function(data) {
dataShare.sendEnvNameDetails(data);
}
$scope.addSlide = function (envName) {
slides.push({
text: envName,
id: currIndex++
});
};
$http.get("http://localhost:8080/getEnvList")
.success(function (data) {
for (var i in data) {
$scope.addSlide(data[i].envName);
}
});
});
Change your controllers and factories:
From:
app.controller('CarouselDemoCtrl', function ($scope, $http, dataShare) { });
To:
angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope, $http, dataShare) { });
From:
app.factory('dataShare',function($rootScope){});
To:
angular.module.factory('dataShare',function($rootScope){});
Related
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>
First time doing an angular application, combining different tutorials but this is the first time I am trying to inject a service.
I have one of my View's controllers like:
angular.module("myApp.Pages").controller('signupController', ['$scope', '$location', '$timeout', 'authService', function ($scope, $location, $timeout, authService) {
}
however am seeing an error when I look at the Console in Developer Tools:
angular.js:12793 Error: [$injector:unpr] Unknown provider:
authServiceProvider <- authService <- signupController
http://errors.angularjs.org/1.5.0-beta.2/$injector/unpr?p0=authServiceProvider%20%3C-%20authService%20%3C-ignupController
My project structure is:
-Client
-App
-Components
-Services
-authService.js
-myAppCore.js
-Views
-app.js
-appRouting.js
-Scripts (References)
-Theme (Css)
-Index.html
My index.html scripts I add:
<!-- Angular References-->
<script src="References/Angular/angular.js"></script>
<script src="References/Angular/angular-route.js"></script>
<script src="References/Angular/angular-ui-router.min.js"></script>
<!-- End Angular References-->
<!-- my app and dependent modules -->
<script src="App/app.js"></script>
<script src="App/appRouting.js"></script>
<!-- Services -->
<script src="App/Components/Services/authService.js"></script>
<!-- END services-->
<!-- Controllers for your pages-->
<script src="App/Pages/Home/homeController.js"></script>
<script src="App/Pages/ContactUs/contactusController.js"></script>
<script src="App/Pages/Entry/entryController.js"></script>
<script src="App/Pages/Signup/signupController.js"></script>
<!-- End Controllers for the page-->
My app.js
angular.module("myApp", [
// User defined modules
'myApp.Templates', // templates
'myApp.Pages', // Pages
'myApp.Core', // Core
// Angular modules
'ui.router', // state routing
'ngRoute', // angular routing
'angular-loading-bar', //loading bar
'LocalStorageModule', //local browser storage
])
and appRouting.js
angular.module("myApp")
.config(["$stateProvider", function ($stateProvider) {
$stateProvider.state('Home', {
url: '/Home',
templateUrl: 'App/Pages/Home/home.html',
controller: 'homeController'
})
.state('Entry', {
url: '/Entry',
templateUrl: 'App/Pages/Entry/entry.html',
controller: 'entryController'
})
.state('Signup', {
url: '/Signup',
templateUrl: 'App/Pages/Signup/signup.html',
controller: 'signupController'
})
.state('Contactus', {
url: '/Contactus',
templateUrl: 'App/Pages/ContactUs/contactus.html',
controller: 'contactusController'
})
.state("otherwise", {
url: "*path",
templateUrl: "App/Pages/NotFound/notFound.html"
});
}])
.run(["$location", function ($location) {
// Go to state dashboard
$location.url('/Home');
}]);
authService which handles login/register:
app.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var serviceBase = '<location>';
var authServiceFactory = {};
var _authentication = {
isAuth: false,
userName: ""
};
var _saveRegistration = function (registration) {
_logOut();
return $http.post(serviceBase + 'api/account/register', registration).then(function (response) {
return response;
});
};
var _login = function (loginData) {
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
var deferred = $q.defer();
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err, status) {
_logOut();
deferred.reject(err);
});
return deferred.promise;
};
var _logOut = function () {
localStorageService.remove('authorizationData');
_authentication.isAuth = false;
_authentication.userName = "";
};
var _fillAuthData = function () {
var authData = localStorageService.get('authorizationData');
if (authData) {
_authentication.isAuth = true;
_authentication.userName = authData.userName;
}
}
authServiceFactory.saveRegistration = _saveRegistration;
authServiceFactory.login = _login;
authServiceFactory.logOut = _logOut;
authServiceFactory.fillAuthData = _fillAuthData;
authServiceFactory.authentication = _authentication;
return authServiceFactory;
}]);
myAppPages.js and myAppCore.js are the same just their respective names :
angular.module("myApp.Pages", []);
Edit: Seeing a "app is not defined" reference error in authService
You don't defined var app, so use angular.module("myApp") to define your factory
angular.module("myApp").factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService)
Also you can declare var app = angular.module("myApp") and use app
I simply did not declare:
var app = angular.module(...)
And my service was referencing app when that did not exist.
var myApp = angular.module("MyApp", ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/cart.php',
controller: 'ctrl',
resolve: {
categories: function(cartService){
console.log('inside resolve categories')
return cartService.getCategories();
}
}
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('ctrl', function (categories, $scope) {
$scope.items = categories;
});
myApp.service("cartService", function ($http, $q) {
this.getCategories = function () {
var deferred = $q.defer();
$http.get('js/categories.js')
.then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}
});
myApp.run(['$rootScope',function($rootScope){
$rootScope.stateIsLoading = false;
$rootScope.$on('$routeChangeStart', function(e, current, pre) {
$rootScope.stateIsLoading = true;
var fullRoute = current.$$route.originalPath;
if(fullRoute == '/')
{
console.log('load categoreis and products')
}
});
$rootScope.$on('$routeChangeSuccess', function() {
$rootScope.stateIsLoading = false;
console.log('route changed');
});
$rootScope.$on('$routeChangeError', function() {
//catch error
});
}]);
I have placed the ng-app and ng-controller directives at the top of the HTML
<html lang="en" ng-app="MyApp" ng-controller="ctrl">
But when I run the HTML I get the following error
Error: [$injector:unpr] Unknown provider: categoriesProvider <-
categories <- ctrl
How can I fix this ?
Edit: If I remove ng-controller="ctrl" from the HTML, then no errors
You got that error just because, you are using the same controller for both index.php and 'partials/cart.php'
Create a separate controller for 'partials/cart.php' to resolve this
problem
Code Snippet:
// Code goes here
var app = angular.module('app', ['ngRoute']);
app.controller('indexCtrl', function($scope) {
$scope.title = 'Header';
});
app.config(function($routeProvider) {
$routeProvider.when('/', {
template: "<ul><li ng-repeat='item in items'>{{item}}</li></ul>",
controller: 'categoryCtrl',
resolve: {
categories: function(cartService){
return cartService.getCategories();
}
}
});
});
app.controller('categoryCtrl', function (categories, $scope) {
$scope.items = categories;
});
app.service("cartService", function() {
this.getCategories = function() {
return ['A', 'B', 'C'];
};
});
<html ng-app="app">
<head>
<script data-require="angular.js#1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script data-require="angular-route#1.4.2" data-semver="1.4.2" src="https://code.angularjs.org/1.4.2/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="indexCtrl">
<h1>{{title}}</h1>
<div ng-view></div>
</body>
</html>
you have to define the categories service/factory which is injected in your controller 'ctrl'.
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
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!