Firebase API issue with AngularJS website example project - javascript

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!

Related

page not displaying with ng-resource

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>

Unknown provider error - AngularJS App issue

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'.

Send data through a POST request from Angular factory

I have this in the controller
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
$scope.formTodoText = '';
};
});
and this in the factory
angular.module('myApp')
.factory('TaskFactory', function ($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
console.log(1, params);
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log(2);
console.log('data', data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTask: function(taskData) {
console.log('taskData', taskData);
return sendTasks('/task/save', {
taskData : taskData
})
}
}
});
all I need is to know, how to send the data from the controller to the factory in order to do the POST to the specified route ?
You just need to call the function/method inside factory with the required params.
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
TaskFactory.sendTask({data : $scope.formTodoText})
$scope.formTodoText = '';
};
});
You can follow Dan Wahlin blog post.
Controller:
angular.module('customersApp')
.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
dataFactory.updateCustomer(cust)
.success(function () {
$scope.status = 'Updated Customer! Refreshing customer list.';
})
.error(function (error) {
$scope.status = 'Unable to update customer: ' + error.message;
});
}
Factory:
angular.module('customersApp')
.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api/customers';
dataFactory.updateCustomer = function (cust) {
return $http.put(urlBase + '/' + cust.ID, cust)
};
}
Hope that solve your problem.
You can call the function directly on the TaskFactory that you pass into the controller as a dependency.
I've cleaned up your code a bit and created a plunk for you here:
And here's the code:
Controller
(function(angular) {
// Initialise our app
angular.module('myApp', [])
.controller('TaskController', function($scope, TaskFactory) {
// Initialise our variables
$scope.todos = [];
$scope.formTodoText = '';
$scope.addTodo = function() {
// Add an object to our array with a 'text' property
$scope.todos.push({
text: $scope.formTodoText
});
// Clear the input
$scope.formTodoText = '';
// Call function to send all tasks to our endpoint
$scope.sendTodos = function(){
TaskFactory.sendTasks($scope.todos);
}
};
});
})(angular);
Factory
(function(angular) {
angular.module('myApp')
.factory('TaskFactory', function($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log('data: ' + data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTasks: sendTasks
}
});
})(angular);

how to inject componenet in angularjs

I am using meanjs(meanjs.org) boiler plate code to build my website and I want to implement file upload feature in the website.
I am using https://github.com/ghostbar/angular-file-model and installed the component and added into bower.json. How do I inject it into my application
Following is the usage written on the website
Install with bower:
bower install angular-file-model --save
Add to your HTML files:
<script src='/bower_components/angular-file-model/angular-file-model.js'></script>
Now, inject to your application:
angular.module('myApp', ['file-model']);
How do I inject in my app?
angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles',
function($scope, $stateParams, $location, Authentication, Articles) {
$scope.authentication = Authentication;
$scope.file = null;
$scope.$watch('file', function (newVal) {
if (newVal) console.log(newVal);
});
$scope.create = function() {
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
$scope.title = '';
$scope.content = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.remove = function(article) {
if (article) {
article.$remove();
for (var i in $scope.articles) {
if ($scope.articles[i] === article) {
$scope.articles.splice(i, 1);
}
}
} else {
$scope.article.$remove(function() {
$location.path('articles');
});
}
};
$scope.update = function() {
var article = $scope.article;
article.$update(function() {
$location.path('articles/' + article._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function() {
$scope.articles = Articles.query();
};
$scope.findOne = function() {
$scope.article = Articles.get({
articleId: $stateParams.articleId
});
};
}
]);
is my controller page. Which can be found at https://github.com/meanjs/mean
my view page is
<section data-ng-controller="ArticlesController" data-ng-init="find()">
<div class="page-header">
<h1>Articles</h1>
</div>
<form>
<input type='file' file-model='file'>
</form>
</section>

Inputting an UUID/GUID into a form's text input using Angular JS

I am creating a form with several input options for the end user, but with one input which I would like to be an UUID/GUID.
Here's what I have so far for the module (project.js):
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://private.firebaseio.com/')
.factory('Projects', function($firebase, fbURL) {
return $firebase(new Firebase(fbURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'list.html'
})
.when('/edit/:projectId', {
controller:'EditCtrl',
templateUrl:'detail.php'
})
.when('/new', {
controller:'CreateCtrl',
templateUrl:'detail.php'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, Projects) {
$scope.projects = Projects;
$scope.project = { trackid: 'UUID' };
})
.controller('CreateCtrl', function($scope, $location, $timeout, Projects) {
$scope.project = { trackid: 'UUID' };
$scope.save = function() {
Projects.$add($scope.project, function() {
$timeout(function() { $location.path('/'); });
});
};
})
.controller('EditCtrl',
function($scope, $location, $routeParams, $firebase, fbURL) {
var projectUrl = fbURL + $routeParams.projectId;
$scope.project = $firebase(new Firebase(projectUrl));
$scope.destroy = function() {
$scope.project.$remove();
$location.path('/');
};
$scope.save = function() {
$scope.project.$save();
$location.path('/');
};
$scope.project = { trackid: 'UUID' };
});
And here's what I have for the form input (in my detail.php file):
<form name="myForm">
<label>Track ID</label>
<input type="text" name="trackid" ng-model="project.trackid" disabled>
As you can tell, in this example I'm simply inserting the text "UUID" where I would actually like to insert an UUID. I can't however seem to figure out how to insert a function there that would be generating this UUID. Any help would be very much appreciated! Thank you!
If you have a function that returns the value needed you can simply do:
function getUUID(){
var result = /* parse value */
return result;
}
$scope.project ={ trackid: getUUID() };
DEMO

Categories

Resources