I would like to store my datas with local storage or cookie. The data source is a json and this json has a data limitation (10 data per page). So I implemented a "show more" function, which is loads the other jsons when I click a button.
My problem is that I can't store properly the whole loaded datas. I tried with different techniques, but nothing.
Here is the html:
<div ng-controller="MyCtrl">
<div ng-repeat="item in items">
<p>{{item.title}}</p>
</div>
<button ng-click="getItems()" ng-hide="items.length == 0">show more</button>
</div>
And here is the controller:
app.controller('MyCtrl', function($scope, $http) {
$scope.items = [];
var page = 1;
$scope.getItems = function () {
var url = 'https://differentdomain.com/json&page=' + page++;
$http({method: 'GET', url: url}).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.items = $scope.items.concat(data.results);
// or other way
// $scope.items.push.apply($scope.items, data.results)
} else {
console.error('Error happened while getting list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the list.')
});
};
$scope.getItems();
});
Anybody has idea, how can I store it the loaded datas?
If all you want to know is hot to store data you can just use localStorage.setItem to save data and localStorage.getItem to retrieve those data.
The simplest implementation would be
app.controller('MyCtrl', function($scope, $http) {
//retrieving saved object or init new array
$scope.getItems = function () {
//XXX if page is last one then return;
//current page is basically num of objects divided by page size (10 in this case)
var page = ($scope.items.length / 10) + 1;
var url = 'https://differentdomain.com/json&page=' + page++;
$http({method: 'GET', url: url}).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.items = $scope.items.concat(data.results);
//saving current object
localStorage.setItem('items', JSON.stringify($scope.items));
} else {
console.error('Error happened while getting list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the list.')
});
};
$scope.items = JSON.parse(localStorage.getItem('items')) || [];
if (!$scope.items.length) $scope.getItems();
});
The above should work, I assume it is loading 10 more each time you click the button.
Your question seems to be how can you persist those loaded items between browser sessions. If so my suggestion would be for you to look at:
https://github.com/goodeggs/angular-cached-resource
This abstracts away all the difficult parts such as persistence and cache retrieval to give you a consistent API.
Related
This code is the same structure as my code:
for (var i in UserNameArray)
{
var Urls = "https://some online api"+UserNameArray[i]+"api key";
//the url changes by plugging in the next array value every iteration.
request({
url: Urls,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
})
}
It returns a json from the URL correctly, but it's printing it out by which every iterated request returns first. How can I change my code so that it prints out the requests in the order that they were requested? This is important as I will have to traverse the specific JSON with a specific value from UserNameArray.
Try this one.
Im going trough all of them, and storing the response in an result array (by index). Then when all of them have finished it goes to a final callback where we print them (in order) to the console.
var async = require('async');
var result = [];
async.eachOf(UserNameArray, function(name, i, cb) {
//the url changes by plugging in the next array value every iteration.
var Urls = "https://some online api"+UserNameArray[i]+"api key";
request({
url: Urls,
json: true
}, function (error, response, body) {
// checking if something went wrong..
if (error) return cb(error);
if (!error && response.statusCode === 200) {
// storing the response to our result array
result[i] = body;
// do a callback, telling that we are done here
cb();
}
})
}, function(err) {
// all done.
// lets print the errors if something went wrong
if (err) console.error(err.message);
// lets print our results
for(var i=0; i<result.length; i++) {
console.log(result[i]);
}
});
Try this before that install async using npm
var async = require('async');
async.forEach(UserNameArray, function (i, cb) {
var Urls = "https://some online api"+i+"apikey";
request({
url: Urls,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
cb();
})
});
I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.
For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?
My AngularJS controller code:
$scope.getResults = function() {
$location.search('color', $scope.myColor);
$location.search('size', $scope.mySize);
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
In Node.js, I have my route like this:
app.get("/results", function (req, res) {
var api = 'some api call/' + req.query.color + '/' + req.query.size;
request(api, function (error, response, api) {
if (!error && response.statusCode == 200) {
res.json({
Response: api
});
}
});
});
In your code you wrote query parameters but you need to read them, try this:
$scope.getResults = function() {
$scope.myColor = $location.search().color;
$scope.mySize = $location.search().size;
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
I am using Ionic Framework and WP-API to develop a mobile app for my Woocommerce based website.I am using the following URL to retriece JSON data about my products from the website -
http://example.com/wp-json/posts?type=product&?_jsonp=JSON_CALLBACK
When I try this URL from my browser, I get a perfect JSON response, with all the required details about my products. However, when i try calling the same URL through Ionic, the framework throughs an error.
UPDATE
$http.jsonp( postsApi ).
success(function(data, status, headers, config) {
$scope.posts = data;
console.log( data );
}).
error(function(data, status, headers, config) {
console.log( 'Post load error.' );
});
Please provide a working link to try it again.
Try using service:
app = angular.module('appName', ['ionic']);
app.factory('postService', function($http){
return {
all: function all() {
var url = 'http://example.com/wp-json/posts?type=product&?_jsonp=JSON_CALLBACK';
return $http.jsonp(url, {cache: true})
.success(function(data){
return data;
}).error(function() {
alert("Error");
});
}
}
});
app.controller("ItemController", function($scope,postService){
$scope.item = [];
postService.all().then(function(data){
data = data.data;
if(data.length == 0){
console.log('empty return');
}else{
$scope.item = data;
}
});
});
I am trying to get data from json API, i am using onsen-ui for creating phonegap app. I am using wordpress plugin to get that.
Here is how i am trying to do this.
module.factory('$data', function($http) {
var data = {};
$http.get('http://www.foduu.com/api/get_recent_posts').
success(function(data, status, headers, config) {
console.log(data.posts);
// return data;
}).
error(function(data, status, headers, config) {
console.log("error in fetching data");
});
});
But this is what i am getting in the console.log.
In HTML i have coded similar to
<ons-list ng-controller="MasterController">
<ons-list-item modifier="chevron" class="item" ng-repeat="item in items" ng-click="showDetail($index)">
<ons-row>
<ons-col width="60px">
<div class="item-thum"></div>
</ons-col>
<ons-col>
<header>
<span class="item-title">{{item.title}}</span>
<span class="item-label">{{item.label}}</span>
</header>
<p class="item-desc">{{item.desc}}</p>
</ons-col>
</ons-row>
</ons-list-item>
</ons-list>
Any suggestions on this will be really helpful.
Thank you
I think you are just missing a return:
module.factory('$data', function($http) {
var data = {};
$http.get('http://www.foduu.com/api/get_recent_posts').
success(function(data, status, headers, config) {
console.log(data.posts);
// return data;
}).
error(function(data, status, headers, config) {
console.log("error in fetching data");
});
return data;
});
As a side note, I suggest that you don't name your own services and factories with a $ prefix. This is an Angular convention for its own provided services.
Also, at the moment, this factory doesn't do much. You should probably return the promise that $http.get returns you:
module.factory('$data', function($http) {
var data = {
getRecentPosts: function() {
return $http.get('http://www.foduu.com/api/get_recent_posts');
}
};
return data;
});
Then handle the promise success and error in the controller that references this factory.
Your factory name should not begin with a $.
Here is an example of a factory that works for me
angular.module('appName')
.factory('FactoryName', function ($http, $q) {
return {
myFunctionName: function (callback) {
var cb = callback || angular.noop;
var deferred = $q.defer();
$http.get('insertYourURLHere')
.success(function (data) {
deferred.resolve(data);
return cb();
}).
error(function (err) {
deferred.reject(err);
return cb(err);
}.bind(this));
return deferred.promise;
},
};
});
Then you can call this in your controller:
$scope.variableName = FactoryName.getProjects()
.then(function(data){
$scope.variableName = data;
})
.catch(function(err){
$log.error(err);
});
Make sure you inject the FactoryName dependency in your controller.
I am using AJAX to get data from a json file, add it to the controller $scope and then use it in ng-repeat. All works fine until I try adding a function to the $scope so it will do another fucntion.
Working OK:
var myApp = angular.module('CouponsApp',[]);
myApp.controller("CouponController",function($scope, $http) {
$http.get('CouponsJSON.json').
success(function(data, status, headers, config) {
$scope.CouponsList = data;
}).
error(function(data, status, headers, config) {
console.log((data || 'Coupons AJAX Req Failed') + ': ' + status);
});
});
ng-repeat stops going over my json and not displaying in my html:
var myApp = angular.module('CouponsApp',[]);
myApp.controller("CouponController",function($scope, $http) {
$http.get('CouponsJSON.json').
success(function(data, status, headers, config) {
$scope.CouponsList = data;
}).
error(function(data, status, headers, config) {
console.log((data || 'Coupons AJAX Req Failed') + ': ' + status);
});
$scope.doStuff()
{
var cellMarkerArray = [];
for(var i=0;i<$scope.CouponsList.CellPhones.length;i++)
{
cellMarkerArray = $scope.CouponsList.CellPhones[i].localVendorAddress;
}
};
});
Any idea?
The point is to add table rows in ng-repeat and it works, but I need an option to press a button and run a function. It doesn't have to be a part of the $scope, but it needs values from one of the table data tags?
$scope.doStuff should be a function.
$scope.doStuff = function()
{
var cellMarkerArray = [];
for(var i=0;i<$scope.CouponsList.CellPhones.length;i++)
{
cellMarkerArray = $scope.CouponsList.CellPhones[i].localVendorAddress;
}
};