Return value from Angular Service - angularjs

Hi I do not understand why always I get empty array from this service when is invoked by my controller
angular
.module('dimecuba.services', [])
.factory('Contacts', function($cordovaContacts, $ionicPlatform) {
var contactsFound = [];
var contacts = {
all:function(){
var options = {};
options.multiple = true;
options.filter = "";
//options.fields = ['displayName'];
options.hasPhoneNumber = true;
$ionicPlatform.ready(function(){
$cordovaContacts.find(options).then(
function(allContacts){
angular.forEach(allContacts, function(contact, key) {
contactsFound.push(contact);
});
console.log("Contacts Found:" + JSON.stringify(contactsFound));
return contactsFound;
},
function(contactError){
console.log('Error');
}
);
});
}
}; //end contacts
console.log("Contacts:"+JSON.stringify(contacts));
return contacts;
});

Use return to chain promises. A return statement needs to be included at each level of nesting.
app.factory('Contacts', function($cordovaContacts, $ionicPlatform) {
var contacts = {
all:function(){
var options = {};
options.multiple = true;
options.filter = "";
options.hasPhoneNumber = true;
//return promise
return $ionicPlatform.ready().then(function() {
//return promise to chain
return $cordovaContacts.find(options)
}).then(function(allContacts){
var contactsFound = [];
angular.forEach(allContacts, function(contact, key) {
contactsFound.push(contact);
});
//return to chain data
return contactsFound;
}).catch(function(contactError){
console.log('Error');
//throw to chain error
throw contactError;
});
}
}; //end contacts
return contacts;
});
In the controller, use the promise returned.
app.controller("myCtrl", function($scope,Contacts) {
var contactsPromise = Contacts.all();
contactsPromise.then( function(contactsFound) {
$scope.contactsFound = contactsFound;
});
});

Related

Angularjs ticker throwing error as shift() is not a function

I am trying to ticker in AngularJs, I am getting error as
shift() is not a function
Please suggest.
$scope.boxes = [];
$scope.moving = false;
$scope.moveLeft = function() {
$scope.moving = true;
$timeout($scope.switchFirst, 1000);
};
$scope.switchFirst = function() {
$scope.boxes.push($scope.boxes.shift());
$scope.moving = false;
$scope.$apply();
};
$interval($scope.moveLeft, 2000);
Update
The following is my controller code
$scope.memoryMap = [];
$scope.loading = true;
myService.getInfo(function(metrics) {
if (metrics) {
$scope.memoryMap = metrics.memoryMap;
}
});
$scope.moving = false;
$scope.moveLeft = function() {
$scope.moving = true;
$timeout($scope.switchFirst, 1000);
};
$scope.switchFirst = function() {
$scope.memoryMap.push($scope.memoryMap.splice(0, 1)[0]);
$scope.moving = false;
$scope.$apply();
};
$interval($scope.moveLeft, 2000);

ngResourc:generate unique number

I'm trying to post new data comment and I want $resource serviceto give every comment unique id automatically.but I don't know how to do it . the data was past but in id was property empty ,it don't have id number.
Code for controller.js
.controller('ContactController', ['$scope','FeedbackFactory', function($scope,FeedbackFactory) {
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" ,id:""};
var channels = [{value:"tel", label:"Tel."}, {value:"Email",label:"Email"}];
$scope.channels = channels;
$scope.invalidChannelSelection = false;
$scope.fback= FeedbackFactory.putFeedback().query(
function(response){
$scope.fback = response;
},
function(response) {
$scope.message = "Error: "+response.status + " " + response.statusText;
}
);
}])
.controller('FeedbackController', ['$scope', 'FeedbackFactory',function($scope,FeedbackFactory) {
$scope.sendFeedback = function() {
console.log($scope.feedback);
if ($scope.feedback.agree && ($scope.feedback.mychannel === "")) {
$scope.invalidChannelSelection = true;
console.log('incorrect');
}
else {
$scope.invalidChannelSelection = false;
$scope.fback.push($scope.feedback);
FeedbackFactory.putFeedback().save($scope.fback);
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" };
$scope.feedback.mychannel="";
$scope.feedbackForm.$setPristine();
console.log($scope.feedback);
}
};
}])
service.js
.service('FeedbackFactory',['$resource','baseURL',function($resource,baseURL){
this.putFeedback = function(){
return $resource(baseURL+"feedback/",{'update':{method:'POST'}});
};
} ])
;
note:the data comment will save in form of JSON data.

One factory accessed by diff. controllers but one at a time angularjs

var app=angular.module('myApp',[]);
app.controller('FCtrl',['$scope','mockFactory',function($scope,mockFactory){
$scope.showPerson = function(){
mockFactory.fetchJson($scope.valueJson)
.then(function(){
$scope.persons = mockFactory.array;
})
}
$scope.delPerson = function(i){
mockFactory.delete(i);
}
$scope.addNamePerson = function() {
mockFactory.ADD($scope.valueFirst);
};
$scope.showConsolePerson= function(){
console.log(JSON.stringify(mockFactory.array));
}
}]);
app.controller('SCtrl',['$scope','mockFactory',function($scope,mockFactory){
$scope.showMovie = function(){
mockFactory.fetchJson($scope.valueJson)
.then(function(){
$scope.movies = mockFactory.array;
})
}
$scope.delMovie = function(i){
mockFactory.delete(i);
}
$scope.addNameMovie = function() {
mockFactory.ADD($scope.valueSecond);
};
$scope.showConsoleMovie= function(){
console.log(JSON.stringify(mockFactory.array));
}
}]);
app.controller('TCtrl',['$scope','mockFactory',function($scope,mockFactory){
$scope.showPlace = function(){
mockFactory.fetchJson($scope.valueJson)
.then(function(){
$scope.places = mockFactory.array;
})
}
$scope.delPlace = function(i){
mockFactory.delete(i);
}
$scope.addNamePlace = function() {
mockFactory.ADD($scope.valueThird);
};
$scope.showConsolePlace= function(){
console.log(JSON.stringify(mockFactory.array));
}
}]);
app.factory('mockFactory',['$http',function($http){
var Precord = {};
Precord.array = [];
Precord.assign = function (value) {
return $http.get('http://localhost:3000/scripts/' + value + '.json');
};
Precord.fetchJson = function(value){
return Precord.assign(value).success(function(response){
Precord.array = response.value;
})
}
Precord.delete = function(i){
Precord.array.splice(i,1);
}
Precord.ADD = function(value){
var newName = {
Name: value
};
Precord.array.push(newName);
}
return Precord;
}]);
How can an array in single factory be accessed by different controllers but one at a time such that any update in one controller must not reflect in other controllers? the precord.array is being used in all the controllers, but i want it to be isolated from other controllers while one controller is in use of it
After reviewing your code I found that you should keep a copy of array on controller level so that, If one controller update it then it will not reflect in other controllers,
I have modified your one controller and your factory, so try to implement it in other controllers also.
Try this
FCtrl
var app=angular.module('myApp',[]);
app.controller('FCtrl',['$scope','mockFactory',function($scope,mockFactory){
$scope.fCtrlJSON = [];
$scope.showPerson = function(){
mockFactory.fetchJson($scope.valueJson)
.then(function(){
$scope.persons = mockFactory.array;
$scope.fCtrlJSON = mockFactory.array;
})
}
$scope.delPerson = function(i){
mockFactory.delete($scope.fCtrlJSON,i);
}
$scope.addNamePerson = function() {
mockFactory.ADD($scope.fCtrlJSON,$scope.valueFirst);
};
$scope.showConsolePerson= function(){
console.log(JSON.stringify($scope.fCtrlJSON));
}
}]);
mockFactory
app.factory('mockFactory',['$http',function($http){
var Precord = {};
Precord.array = [];
Precord.assign = function (value) {
return $http.get('http://localhost:3000/scripts/' + value + '.json');
};
Precord.fetchJson = function(value){
return Precord.assign(value).success(function(response){
Precord.array = response.value;
})
}
Precord.delete = function(arrayData, i){
arrayData.splice(i,1);
}
Precord.ADD = function(arrayData, value){
var newName = {
Name: value
};
arrayData.push(newName);
}
return Precord;
}]);

Delay loading data in Angular JS

I have code like this
(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this?
Since you are loading data via api call, there will be a delay. To handle this delay, you should display a loading screen. Once the data is loaded, the loading screen gets hidden and your main screen is visible. You can achieve this using $http interceptors.
See : Showing Spinner GIF during $http request in angular
The api-call is almost certainly causing the delay. Data may be received slowly via the api-call so you could display any sort of loading text/image to notify the use that the data is being loaded.
If u want the data ready at the time when controller inits, u can add a resolve param and pass the api call as a $promise in the route configuration for this route.

Angularjs/Ionic DB result with promise

I have a simple query that I am struggling with:
.factory('Config', function($http, DB) {
var self = this;
self.setValue = function(key,value) {
console.log('setValue(value)', value);
return DB.query("UPDATE config SET value = '"+value+"' WHERE key = '"+key+"'")
.then(function(result){
return DB.fetchAll(result);
});
}
self.getValue = function(key) {
return DB.query("SELECT value FROM config WHERE key = '"+key+"'")
.then(function(result){
return DB.fetchOne(result);
});
};
return self;
})
with the following code in controller.js under the heading:
.factory('DB', function($q, DB_CONFIG) {
var self = this;
self.db = null;
(I took the init part of the function away for the sake of simplicity. Also DB is working well when inserting, getting and updating data.)
self.fetchOne = function(result) {
var output = null;
output = angular.copy(result.rows.item(0));
return output;
};
self.query = function (sql, bindings) {
bindings = typeof bindings !== 'undefined' ? bindings : [];
var deferred = $q.defer();
self.db.transaction(function (transaction) {
transaction.executeSql(sql, bindings, function (transaction, result) {
deferred.resolve(result);
}, function (transaction, error) {
deferred.reject(error);
});
});
return deferred.promise;
};
self.fetchAll = function (result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
};
Called like so:
$scope.config.recordar = Config.getValue("recordar");
Doing a console.log returns:
I am struggling to access the value: "true" which is highlighted in BLUE in the above image.
Any leads?
$scope.config.recordar = Config.getValue("recordar");
Does not work (ala JS). It has to be called like so:
Config.getValue("recordar").then(function(data) {
$scope.config.recordar
});
I assume that you shall change your function declaration from :
self.setValue = function(key,value) {
console.log('setValue(value)', value);
return DB.query("UPDATE config SET value = '"+value+"' WHERE key = '"+key+"'")
.then(function(result){
return DB.fetchAll(result);
});
}
to
self.setValue = function(key,value) {
console.log('setValue(value)', value);
DB.query("UPDATE config SET value = '"+value+"' WHERE key = '"+key+"'")
.then(function(result){
return DB.fetchAll(result);
});
}
You will return the result of your promise, not your promise
I have changed "return DB..." to "DB..."

Resources