$firebaseArray is not a function? - angularjs

I am creating a firebase blog app. I am experiencing a problem in a controller of mine where TypeError: $firebaseArray is not a function
I have been using $firebaseArray throughout the entire span of the app. I don't know how I broke it. I can show you the code to my controller.
app.controller('postController',["$scope", "$location","$routeParams","Blog","FBURL","Auth","authDataSrvc", "$firebaseObject", "$firebaseArray","FilePicker", "$window", function($scope,$location,$routeParams,Blog,FBURL,$firebaseArray,$firebaseObject,FilePicker,$window,Auth,authDataSrvc){
$scope.posts = Blog.allPosts; //All blog posts
var postId = $routeParams.postId;
if(postId){
$scope.selectedPost = getPost(postId); // gets unique object based on its id with get post function
}
function getPost(postId){
var ref = new Firebase(FBURL + "/" + postId);
return $firebaseArray(ref);
}
$scope.addPost = function(newpost){
Blog.addPost($scope.newpost);
$location.path('/'); //redirects to home page
console.log(newpost);
console.log($scope.posts); // all posts
$scope.newpost ={}; //reset the message
};
$scope.currentPost = function(postId){
Blog.getPost(postId);
console.log(postId);
};
$scope.editPost = function(post){
$scope.selectedPost.$save(post);
$location.path('/');
};
$scope.files = [];
$scope.pickFile = function(){
FilePicker.pickMultiple(
{
mimetype: 'image/*',
maxFiles: 4
},
$scope.onSuccess
);
};
$scope.onSuccess = function(Blobs,newpost){
$scope.files.push(Blobs); //push to filepicker
var imageURLs = []; //new image urls array
Blobs.forEach(function(file){
imageURLs.push(file.url); //inserts Blob.urls to imageURLs array
});
$scope.newpost['photo'] = imageURLs; //adds photo urls array to newpost.photo which stores to firebase 'newpost object'
console.log(Blobs.url);
$window.localStorage.setItem('files', JSON.stringify(Blobs.url));
};
// COMMENTS SECTION
/* {
}*/
$scope.createComment = function(post, message){
var profilePic;
var profileName;
/* Check to see social media provider before pushing that information */
if($scope.authData.provider === 'facebook'){
profilePic = $scope.authData.facebook.profileImageURL;
profileName = $scope.authData.facebook.displayName;
}
else if($scope.authData.provider === 'google'){
profilePic = $scope.authData.google.profileImageURL;
profileName = $scope.authData.google.displayName;
}
//console.log(profilePic,profileName);
var ref = new Firebase(FBURL + "/" + postId + "/comments/");
var fireCommentArray = $firebaseArray(ref);
return fireCommentArray.$set(
{
text: $scope.message.text,
pic: $scope.profilePic,
name: $scope.profileName
}
),
$scope.message = '';
};
$scope.removeComment = function(post, message) {
var commentForDeletion = new Firebase(FBURL + "/" + postId + "/comments/" + message.$id);
commentForDeletion.$remove();
};
Right now it errors out on getPost function, $scope.addCommentFunction which are both using $firebaseArray.$add() calls.
My app does have separated services and directives as well but everything seems to be intact with no errors.

Your $firebaseArray object gets injected as 9th parameter, but the variable $firebaseArray is the 6th parameter.
Try this instead:
app.controller('postController', [
"$scope", "$location", "$routeParams", "Blog", "FBURL",
"Auth", "authDataSrvc", "$firebaseObject", "$firebaseArray", "FilePicker",
"$window",
function(
$scope, $location, $routeParams, Blog, FBURL,
Auth, authDataSrvc, $firebaseObject, $firebaseArray, FilePicker,
$window
){
... or remove the ["$scope", "$location", "$routeParams", "Blog"... altogether if you don't mangle your variable names through a compressor or obfuscator.

Related

retrieving one record form firebase database. Ionic App

Hi I'm doing an application in Ionic Creator and I would like to retrieve one record from database that has given email address (userId) .
this is my code:
function ($scope, $stateParams, $firebaseArray, $ionicUser, $state, $ionicAuth) {
$scope.userData = $ionicUser.details;
$scope.data = {
'points': ''
}
$scope.logout = function(){
$ionicAuth.logout();
$state.go('tabsController.login');
};
var userId = $ionicUser.details.email;
var ref = firebase.database().ref().child('/users/' + userId);
$scope.users = $firebaseArray(ref);
}
but if my code is like that it works fine but display all the data from database:
function ($scope, $stateParams, $firebaseArray, $ionicUser, $state, $ionicAuth) {
$scope.userData = $ionicUser.details;
$scope.data = {
'points': ''
}
$scope.logout = function(){
$ionicAuth.logout();
$state.go('tabsController.login');
};
var ref = firebase.database().ref().child( "users");
// create a synchronized array
$scope.users = $firebaseArray(ref);
}
Any help would be super appreciated.
inject $firebaseObject into the controller and then do
var ref = firebase.database().ref().child('/users/');
$scope.user = $firebaseObject(ref.child(userId));

I am Using ng-table for both admin and user with different source. author data shows in admin, till refresh

I am using ng-table for admin and user with same controller, same view but loaded data with different URL, but while getting data from cache it reloads data from cache, (which I want to clear when the user logs out)
Controller
myApp.controller('listArticle', ['$scope', '$filter', 'ngTableParams', 'nameService', '$rootScope', '$location', '$timeout', '$cookieStore', 'flashService', '$templateCache',
function ($scope, $filter, ngTableParams, nameService, $rootScope, $location, $timeout, $cookieStore, flashService, $templateCache)
{
//$templateCache.removeAll();
$scope.success = {};
$scope.article = {};
$scope.article.edit = '-';
$scope.article.approve = '-';
$scope.article.view = 'view';
$scope.showAlert = true;
flashService.displayAlertMessages();
$scope.tableParams = new ngTableParams(
{
page: 1, // show first page
count: 10, // count per page
sorting: {name: 'asc'}
},
{
total: 0, // length of data
getData: function ($defer, params)
{
nameService.getData($defer, params, $scope.filter);
},
counts: [],
paginationMaxBlocks: 13
});
$scope.$watch("filter.$", function ()
{
$scope.tableParams.reload();
});
}]);
Service
myApp.service("nameService",['$http','$filter','$cookieStore', '$rootScope', function($http, $filter, $cookieStore, $rootScope){
function filterData(data, filter)
{
return $filter('filter')(data, filter);
}
function orderData(data, params)
{
return params.sorting() ? $filter('orderBy')(data, params.orderBy()) : filteredData;
}
function sliceData(data, params)
{
return data.slice((params.page() - 1) * params.count(), params.page() * params.count());
}
function transformData(data,filter,params)
{
return sliceData( orderData( filterData(data,filter), params ), params);
}
var service =
{
cachedData:[],
getData:function($defer, params, filter)
{
if(service.cachedData.length>0)
{
var filteredData = filterData(service.cachedData,filter);
transformedData = sliceData(orderData(filteredData,params),params);
params.total(filteredData.length);
$defer.resolve(transformedData);
}
else
{
var id = $cookieStore.get('userId');
if($rootScope.role == 1)
{
var url = "article/serverside/fetch-pending-list.php";
var data = "";
}
else
{
var url = "article/serverside/fetch-list.php";
var data = {id:id};
}
$http.post(url,data)
.success(function(resp)
{
var i=0;
for(i=0; i<resp.length; i++)
{
resp[i].status = parseInt(resp[i].status);
resp[i].category = parseInt(resp[i].category);
if($rootScope.role > 1)
resp[i].edit = (resp[i].status == 1)?"Edit":"";
else{
resp[i].approve = (resp[i].status == "2")?"Approve/Reject":"";
}
var j=0;
var k=0;
for(j=0;j<statusList.length;j++){
if(statusList[j]['id'] == resp[i].status)
resp[i].status = statusList[j]['title'];
}
for(k=0;k<categories.length;k++){
if(categories[k]['id'] == resp[i].category)
resp[i].category = categories[k]['title'];
}
}
angular.copy(resp,service.cachedData);
params.total(resp.length);
var filteredData = $filter('filter')(resp, filter);
transformedData = transformData(resp,filter,params);
$defer.resolve(transformedData);
});
}
}
};
return service;
}]);
Note if(service.cachedData.length>0) This place same data loaded on both logins.Also like, If I save a form of data and redirect to ng-table the list is not updated, since it loads data from cache not from source.
You should explicitly clear cachedData array when user logs out so that new user will have fresh array of cached objects.
Or store the cachedData with key way. e.g.
cachedData=[{"user" : '123', 'data':[{}]},
"user" : '234', 'data':[{}]
]
this will add some complications as you will need to query cachedData based on user id.
Why not you use angular cache service which does this work automatically (i.e. it creates separate cache for different urls). https://github.com/jmdobry/angular-cache
Edit:To clear the cache on log out;
If you have a auth controller (the controller that handles login and log out action). Inject the nameService in to that controller On click of logout you can simple write nameService.cachedData = [].

TypeError: Cannot read property 'push' of null

I made a Todo app with Angularjs and Ionic.
I want to save to localStorage some fields, but when i click save I get this error.
My code is:
angular.module('myApp', ['ionic'])
.controller('myAppCtrl', function($scope){
$scope.uuid = function(){
return Math.floor(( 1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
$scope.todo = {};
$scope.todos = {};
//Check The Localstorage If the Todos exists
var todos = localStorage.getItem('todos');
if(todos !== undefined){
$scope.todos = JSON.parse(todos);
}
$scope.addTodo = function($event){
activate_page("#create_edit");
};
$scope.goBack = function($event){
activate_page("#mainpage");
};
$scope.saveTodo = function($event){
$scope.todo.id = $scope.uuid();
$scope.todos.push($scope.todo);
$scope.todo = {};
localStorage.setItem('todos', JSON.stringify($scope.todos)); //Save
activate_page("#mainpage");
};
});
Can you help me?
Thank you
You need to declare and initialize the variable $scope.todos like below since you are pushing to an object not array
$scope.todos = [];
You are trying to push to a JSON object, not an array, which is defined like so:
$scope.todos = [];

Redirect only after $save success in AngularJS

I am POSTing a form and I want to redirect to my list page in case the form has no errors/is successfully persisted/saved to the db. How do I achieve that ?
app.controller('NoteCreateController',
['$scope', 'Note', '$routeParams', '$location','ShareNoteScope',
function($scope, Note, $routeParams, $location, ShareNoteScope) {
$scope.notes = ShareNoteScope.getScope().notes;
$scope.newNote = {};
$scope.createNote = function(note) {
var newNote = new Note(note);
newNote.$save(function(newNote) {
$scope.notes.unshift(newNote.note);
$scope.note = '';
$scope.errors = '';
}, function(newNote) {
$scope.errors = newNote.data;
// $location.path('/notes/'+newNote.note.id); where do I put this?
});
}
}]);
$save wraps success call with a callback. The piece of code above should do the trick.
newNote.$save(function (newNote) {
//success callback
$location.path('/notes/' + newNote.note.id);
}, function (newNote) {
$scope.errors = newNote.data;
});

AngularJS $http.post method doesn't sending data to Grails Action

My Grails application doesn't receiving data from angularjs post request.
My AngularJS Controller is:
module.controller('MemberCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.submitForm = function () {
$http.post(uri + "receiveNewMember", $scope.member)
.success(function (data) {
console.log("Data Sent With Success! " + data);
})
.error(function (data) {
console.log("Fail");
});
};
}]);
My Grails Action is:
def receiveNewMember(){
render text: params.name
}
The Debugger Stops into action. But params variable hasn't any data but controller and action.
Someone knows how can I fix this?
The Post Data can be accessed via request.JSON in Grails Controller.
You can do something like this to emulate the way grails works:
post query parameters like jQuery
Also I created a Serializer factory to serialize any kind of javascript object to the expected way on grails:
(function() {
'use strict';
angular.module('app').factory('Serializer', function ($filter) {
function SerializerService(){}
var serializerService = new SerializerService();
serializerService.excludedProperties = ['$$hashKey'];
SerializerService.prototype.serialize = function(object){
var results = {};
this.serializeObject(results, object, "");
return results;
};
SerializerService.prototype.serializeObject = function(results, object, nameAtTheMoment){
if($.isArray(object)){
var array = object;
for (var i=0; i<object.length; i++){
var newNameAtTheMoment = nameAtTheMoment + "[" + i.toString() + "]";
this.serializeObject(results, array[i], newNameAtTheMoment)
}
}
else{
if(Object.prototype.toString.call( object ) === "[object Object]"){
var i=0;
for(var property in object){
if (object.hasOwnProperty(property) && this.excludedProperties.indexOf(property) == -1) {
var newNameAtTheMoment;
if(nameAtTheMoment !== "")
newNameAtTheMoment = nameAtTheMoment + "." + property;
else
newNameAtTheMoment = property;
this.serializeObject(results, object[property], newNameAtTheMoment);
i++;
}
}
}
else{ //the object is a simple value
if(Object.prototype.toString.call(object) === '[object Date]'){
var dateServerFormat = window.appConfig.dateServerFormat;
results[nameAtTheMoment] = $filter('date')(object, dateServerFormat);
}
else
results[nameAtTheMoment] = object;
}
}
};
return serializerService;
});
})();
And following the first link description you can do something like this:
angular.module('app', [...])
.config(function ($provide, $httpProvider) {
var serializer;
// Trick to inject dependencies on the config function.
$provide.factory('FactoryInjector', function () {
return {
setSerializer: function(serializerParam){
serializer = serializerParam;
}
};
});
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? $.param(serializer.serialize(data)) : data;
}];
})
.run(function ($rootScope, $state, $stateParams, Serializer, FactoryInjector) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
FactoryInjector.setSerializer(Serializer);
});

Resources