angularJS ng-repeat issue - adding a function to the $scope - json

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;
}
};

Related

Ionic Framework giving error while displaying json 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;
}
});
});

How to use HTTP.GET in AngularJS correctly? (Dynamically)

I create it has a service, and then pass it to my controller, The problem is that i have it to read a static file only (1.json), and now that i have populated this folder with more than one json, i would like to know, how can I bring them all in, and make this call dynamically.
Service:
todoApp.factory('eventData', function($http, $q){
return {
getEvent: function(){
var deferred = $q.defer();
$http({method: 'GET', url: '/data/phonebook/1'}).
success(function (data, status, headers, config){
deferred.resolve(data);
}).
error(function (data, status, headers, config){
deferred.reject(status);
});
return deferred.promise;
}
};
});
Controller:
todoApp.controller('FeederController',
function FeederController($scope, eventData) {
eventData.getEvent().then(
function(event){$scope.event = event;},
function(statusCode) {console.log(statusCode)});
}
);
Best Wishes
You'll want to parameterize your service call. Once there you can just change your code to handle 1=>N calls rather than one using a loop.
todoApp.factory('eventData', function($http, $q){
return {
getEvent: function(id){
var deferred = $q.defer();
$http({method: 'GET', url: '/data/phonebook/'+id}).
success(function (data, status, headers, config){
deferred.resolve(data);
}).
error(function (data, status, headers, config){
deferred.reject(status);
});
return deferred.promise;
}
};
});
and your controller becomes
todoApp.controller('FeederController',
function FeederController($scope, eventData) {
$scope.events = [];
for(var i=0; i<10; i++){
eventData.getEvent(i).then(
function(event){$scope.events.push(event);},
function(statusCode) {console.log(statusCode)});
}
}
);
It is good to keep consistent when using .then() vs. .success(). Also, you can use the $http.get() method.
todoApp.factory('eventData', function($http, $q){
return {
getEvent: function(id){
var deferred = $q.defer();
$http.get('/data/phonebook/' + id).then(function(data) {
deferred.resolve(data);
}, function (data, status) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
Then you can get the id of your choice by passing in the id you need.
todoApp.controller('FeederController',
function FeederController($scope, eventData) {
$scope.GetEvent = function(id) {
eventData.getEvent(id).then(function(event){
$scope.event = event;
}, function(statusCode) {
console.log(statusCode);
});
};
});
Then get the info how ever you want.

AngularJS - store page data

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.

unable to fetch data from json API wordpress throught AngularJS + Onsen

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.

Using return $q.when in Hot Towel Angular datacontext

I've created a web application using the Hot Towel Angular template, and I want to add a service function to the 'datacontext'.
Code is:
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId, ['common', '$http', datacontext]);
function datacontext(common, $http) {
var $q = common.$q;
var service = {
getFunctions: getFunctions
};
return service;
function getFunctions() {
var f = [];
$http({
method: 'GET',
url: 'https://api.github.com/users/google/repos',
contentType: 'application/json; charset=utf-8'
})
.success(function (data, status, headers, config) {
f = data;
console.log('f=*' + f + '*');
})
.error(function (data, status, headers, config) {
alert('error!');
});
return $q.when(f);
}
}
})();
I see that the console shows some objects:
f=*[object Object],[object Object],[object O...
But when using this in my functionController.js file :
function getFunctions() {
return datacontext.getFunctions().then(function (data) {
console.log('data=*' + data + '*');
return vm.functions = data;
});
}
The value for data is set to undefined.
I'm missing something, please help identify the error.
Solution:
The getFunctions function in the datacontext should return the $http promise object, like this:
function getFunctions() {
return $http.get('https://api.github.com/users/google/repos')
.error(function (data, status, headers, config) {
alert('error ! : ' + status);
});
}
And in the controller, you can use the returned json object as follows:
function getRepos() {
return datacontext.getRepos().then(function (httpResult) {
vm.repos = httpResult.data;
});
}