I am trying to clean the JSON data i have i.e. remove the N/A and null data. I am trying to use $.each to clean the data however it has no effect on the data.
.controller('APICtrl', function($scope, $http, $localstorage, $window, $state, $sce) {
// Search function
//var offices = [];
var n;
$scope.query = {}
$scope.queryBy = '$'
// gets the data from offices.json
$http.get('js/offices.json').then(function(resp) {
console.log('Success', resp);
$scope.offices = $.each(resp.data.office, function(key,value){
//console.log(value);
if(value==""||value==null){
delete resp.data.office[key];
}
});
//console.log(offices)
}, function(err) {
console.error('ERR', err);
// err.status will contain the status code
});
instean jquery functions
$scope.offices = $.each(resp.data.office, function(key,value){
use standart angular functions
$scope.offices = angular.forEach(resp.data.office, function(key,value){
https://docs.angularjs.org/api/ng/function/angular.forEach
Do you have jQuery included? Otherwise my guess is that you're getting an error that is being silenced because it's inside of a then. This should work:
.controller('APICtrl', function($scope, $http, $localstorage, $window, $state, $sce) {
// Search function
//var offices = [];
var n;
$scope.query = {};
$scope.queryBy = '$';
// gets the data from offices.json
$http.get('js/offices.json').then(function(resp) {
console.log('Success', resp);
var office = resp.data.office;
angular.forEach(office, function(value, key){
if (value == "" || value == null) {
delete office[key];
}
});
$scope.offices = office;
//console.log(offices)
}, function(err) {
console.error('ERR', err);
// err.status will contain the status code
});
});
Related
I am very new to AngularJS.
I want to pass an array data from my app factory to app controller.
Here is my app.factory code.
App.factory('buyFactory', ['$http', function($http) {
factory.Search = function(scope, d) {
var data = scope.search;
scope.CarsData = [];
all_cars = [];
scope.isLoading = true;
$http.post(ajaxurl + '?action=search_car', d)
.success(function(response) {
angular.forEach(response, function(c) {
c.price = parseFloat(c.price);
c.driven = parseFloat(c.driven);
c.year = parseFloat(c.year);
});
angular.forEach(response, function(value, key) {
all_cars.push(value);
scope.CarsData = all_cars;
scope.TotalItems = scope.CarsData.length;
scope.isLoading = false;
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
scope.isLoading = false;
});
}
return factory;
}]);
and this is app.controller as
App.controller('buyController', ['$scope', '$http', 'buyFactory', '$filter', function($scope, $http, buyFactory, $filter) {
$scope.CarsScroll = buyFactory.Search.CarsData();
$scope.loadMore = function() {
var last = $scope.CarsScroll[$scope.CarsScroll.length - 1];
for (var i = 1; i <= 3; i++) {
$scope.CarsScroll.push(last + i);
}
};
//scroll
}]);
I want to use output obtained from factory i.e. CarsData as a variable in my app controller. But I am not able to get it. I have tried using services also. Is there method to use array data in a simplest way.
Your syntax is completely broken, i would recommend following any course of AngularJS. As for how to correctly do what you are trying to would look something like this
app.factory('buyFactory', ['$http', '$q', function($http, $q) {
var factory = {
search: function(d) {
return $q(function(resolve, reject) {
$http.post(ajaxurl + '?action=search_car', d).then(function(response) {
angular.forEach(response, function(c) {
c.price = parseFloat(c.price);
c.driven = parseFloat(c.driven);
c.year = parseFloat(c.year);
});
var carsData = [];
angular.forEach(response, function(value, key) {
carsData.push(value);
})
var result = {
carsData: carsData,
total: carsData.length
}
resolve(result);
}, function(error) {
reject(error);
})
});
}
}
return factory;
}]);
app.controller('buyController', ['$scope', '$http', 'buyFactory', '$filter', function($scope, $http, buyFactory, $filter) {
buyFactory.search().then(function(result) {
var cars = result.carsData;
var total = result.total;
})
}]);
Note: i do not know what the d parameter is for neither why the angular.forEach statements so it might not be fully functional. But this is more as guideline for how your factory should look and be used.
So, I have created a factory to query the db and return data. Inside the method, I can print to the console. But when I check the return data from inside a controller, it's empty, please look at the code below and see if you can help.
Here is the factory
rs.factory("userService",function($http,$ionicLoading,$cordovaProgress,$cordovaSQLite,$q){
var user = {};
/**get user data */
user.getData = function(){
//stores from the local database
var userData = [];
var query = "SELECT * FROM users";
$cordovaSQLite.execute(db, query, []).then(function(res) {
for (var i=0; i < res.rows.length; i++){
userData.push(res.rows.item(i));
}
console.log("User Data : " + JSON.stringify(userData));//this works
}, function (err) {
console.error(err);
})
return userData;
};
return user;
});
The controller:
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout, $http, $state, $cordovaSQLite,$ionicNavBarDelegate,userService) {
console.log(userService.getData()); // is empty
})
Nothing is returned here.
1st thing you need to return a userData from success callback of your promise, & thereafter return $cordovaSQLLite.execute promise, so that you can chain that promise inside controller
user.getData = function() {
//stores from the local database
var userData = [];
var query = "SELECT * FROM users";
//returning promise
return $cordovaSQLite.execute(db, query, []).then(function(res) {
for (var i = 0; i < res.rows.length; i++) {
userData.push(res.rows.item(i));
}
//return data once user Data created
return userData;
}, function(err) {
console.error(err);
})
};
Then inside controller you could access data by having .then function over that method
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout, $http, $state, $cordovaSQLite,$ionicNavBarDelegate,userService) {
userService.getData().then(function(userData){
console.log(userData);
});
})
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;
});
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);
});
i am trying to display data from firebase and i have below code. I already declared firebase dependency for my app.
.controller('AdvMainCtrl', ['$scope', 'dataLoad',
function($scope, dataLoad, $route, $routeParams, $location, $resource, angularFire) {
var categoryPromise = dataLoad.loadCategories($scope, 'categories'),
tmPromise = dataLoad.loadTransportationMode($scope, 'tModes'),
tourPromise = dataLoad.loadAdventures($scope, 'tours');
categoryPromise.then(function() {
console.log('data loaded');
});
$scope.$watch('category', function() {
if (typeof $scope.category === 'undefined') return;
console.log('category changed');
console.log($scope.category.name);
});
$scope.$watch('tMode', function() {
if (typeof $scope.tMode === 'undefined') return;
console.log('tm changed');
//console.log($scope.transportationMode.name);
});
var ref = new Firebase("https://wpladv.firebaseio.com/adventure");
$scope.tours = [];
angularFire(ref, $scope, "tours");
}
])
in the console i see the error occurring at angularFire(ref, $scope, "tours"); statement. I am not sure how to fix this.
the entire code in my controller is
.controller('AdvMainCtrl', ['$scope', 'dataLoad',
function($scope, dataLoad, $route, $routeParams, $location, $resource, angularFire) {
var categoryPromise = dataLoad.loadCategories($scope, 'categories'),
tmPromise = dataLoad.loadTransportationMode($scope, 'tModes'),
tourPromise = dataLoad.loadAdventures($scope, 'tours');
categoryPromise.then(function() {
console.log('data loaded');
});
$scope.$watch('category', function() {
if (typeof $scope.category === 'undefined') return;
console.log('category changed');
console.log($scope.category.name);
});
$scope.$watch('tMode', function() {
if (typeof $scope.tMode === 'undefined') return;
console.log('tm changed');
//console.log($scope.transportationMode.name);
});
var ref = new Firebase("https://wpladv.firebaseio.com/adventure");
$scope.tours = [];
angularFire(ref, $scope, "tours");
}
])
the error is showing at "var categoryPromise = dataLoad.loadCategories($scope, 'categories')," statement
i have the following code in my api js file.
angular.module('localAdventuresApp')
.factory('dataLoad', ['angularFire',
function(angularFire) {
var dbUrl = 'https://wpladv.firebaseio.com/';
return {
loadCategories: function(scope, items) {
var cat = '/category';
return angularFire(dbUrl + cat, scope, items, []);
},
loadTransportationMode: function(scope, items) {
var cat = '/transportMode';
return angularFire(dbUrl + cat, scope, items, []);
},
loadAdventures: function(scope, items) {
var cat = '/adventures';
return angularFire(dbUrl + cat, scope, items, {});
}
}
}
])
the error is being displayed in the "return angularFire(dbUrl + cat, scope, items, []);" statement here. The error which i am seeing in my console is "Error: Please provide a Firebase reference instead of a URL, eg: new Firebase(url)".
you need to inject the dependencies to your controller
.controller('AdvMainCtrl', ['$scope', 'dataLoad', '$route', '$routeParams', '$location', '$resource', 'angularFire',
function($scope, dataLoad, $route, $routeParams, $location, $resource, angularFire) {
// your code here
}
])
the error "Please provide a Firebase reference instead of a URL, eg: new Firebase(url)" was occuring because i had angularfire version > 0.3.0. All i had to do was to change dbUrl + cat to new Firebase(dbUrl + cat). That fixed the issue. Thank you all for your valuable suggestions.
code after change
angular.module('localAdventuresApp')
.factory('dataLoad', ['angularFire',
function(angularFire) {
var dbUrl = 'https://wpladv.firebaseio.com';
return {
loadCategories: function(scope, items) {
var cat = '/category';
console.log(dbUrl);
var ref = new Firebase(dbUrl + cat);
return angularFire(ref, scope, items, []);
},
loadTransportationMode: function(scope, items) {
var cat = '/transportMode';
var ref = new Firebase(dbUrl + cat);
return angularFire(ref, scope, items, []);
},
loadAdventures: function(scope, items) {
var cat = '/adventure';
var ref = new Firebase(dbUrl + cat);
return angularFire(ref, scope, items, {});
}
}
}
])