How can i display JSON data inside pagination using Angularjs? - javascript

[
{
"id": "1",
"titlu": "client1",
"subtitlu": "client1",
"continut": "client1 is ...",
"bigimage": "images/client1.jpg",
"smallimage1": "images/client1.jpg",
"smallimage2": "images/client1.jpg",
"smallimage3": "images/client1.jpg",
"smallimage4": "images/client1.jpg"
},
{
"id": "2",
"titlu": "client2",
"subtitlu": "client2",
"continut": "client2 is ...",
"bigimage": "images/client2.jpg",
"smallimage1": "images/client2.jpg",
"smallimage2": "images/client2.jpg",
"smallimage3": "images/client2.jpg",
"smallimage4": "images/client2.jpg"
},
{
"id": "3",
"titlu": "client3",
"subtitlu": "client3",
"continut": "client3 is ...",
"bigimage": "images/client3.jpg",
"smallimage1": "images/client3.jpg",
"smallimage2": "images/client3.jpg",
"smallimage3": "images/client3.jpg",
"smallimage4": "images/client3.jpg"
}
]
This is my client.json, I want to load the page at a time, each index of json. Something like PREV button, and will load previous id from json on my page. Can someone give me a link or something to help me.
Controller.js
animateApp.controller('projectsController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http){
$http.get('res/json/client.json').success(function(data){
$scope.projects = data;
$scope.currentProject = 1;
});

Try this link which has data and you can bind them with your control.
JSON Link
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
for(var attr in item) {
if (searchMatch(item[attr], $scope.query))
return true;
}
return false;
});

Related

Loading Bar in table Angular

Hello here's my json :
[
{
"name": "AAAAAA",
"loading": "False",
},
{
"name": "BBBBBB",
"loading": "45%",
},
{
"name": "CCCCCC",
"loading": "12%",
},
{
"name": "DDDDDD",
"loading": "False",
}
]
My javascript :
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('names.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function() {
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
HTML :
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.loading}}</td>
</tr>
</tbody>
What i try to do is loading bar for name.loading %. I get it from server, and the % is loading for something, so it still load (ex. in first second 15%, in second 25%...), and when its 100% name.loading = "False". I need loading bar in the table name.loading, only when its %, when its "False", in table should be just "False".
Thanks in advance
You can use progress in html5.
Edit your code like below.
<td><progress value="{{name.loading}}" max="100" ng-if="name.loading != 'False'">{{name.loading}} %</progress></td>
You can use ngIf directive to achieve that.
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td ng-if="name.loading !== 'False'">{{name.loading}}</td>
</tr>
</tbody>

Passing ng-repeat data into another function

I wish to pass the detail of an order displayed in an ng-repeat to another function in my controller. I have it working with the first item in my array. How can I expand to display whichever order I have on that page?
When you click on the detail button it creates the required URL, I need this to be created whichever order is currently displayed on the detail page. Working with the first item in the array, can it be expanded to other orders?
https://plnkr.co/edit/nASmvcPakxKpRXDsfKnW?p=catalogue
app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('tabs', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('tabs.home', {
url: '/home',
views: {
'home-tab' : {
templateUrl: 'templates/home.html'
}
}
})
.state('tabs.list', {
url: '/list',
views: {
'list-tab' : {
templateUrl: 'templates/list.html',
controller: 'ListController'
}
}
})
.state('tabs.detail', {
url: '/list/:aId',
views: {
'list-tab' : {
templateUrl: 'templates/detail.html',
controller: 'ListController'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/home');
})
.controller('ListController', ['$scope', '$http', '$state','$cordovaBluetoothSerial', '$window', '$location', function($scope, $http, $state, $cordovaBluetoothSerial, $window, $location) {
$http.get('js/aboDATAONLY.json').success(function(data) {
$scope.orders = data;
$scope.whichorder = $state.params.aId;
})
$scope.orders = [];
function onPay() {
var itemsArr = [];
var invoice = {};
var myItems = {};
var myItem = {};
var order = $scope.orders[0];
myItem['name'] = order.bkev_name;
myItem['description'] = "A robotic ball that can be controlled via apps";
myItem['quantity'] = bkor_seatcount;
myItem['unitPrice'] = order.bkor_subtotal;
myItem['taxRate'] = '0.0';
myItem['taxName'] = 'Tax';
itemsArr.push(myItem);
myItems['item'] = itemsArr;
invoice['itemList'] = myItems;
invoice['paymentTerms'] = 'DueOnReceipt';
invoice['currencyCode'] = 'GBP';
invoice['discountPercent'] = '0';
invoice['merchantEmail'] ='email#email.com';
invoice['payerEmail'] = 'foo#bar.com';
var returnUrl = order.bkor_seatcount;
var retUrl = encodeURIComponent(returnUrl + "?{result}?Type={Type}&InvoiceId={InvoiceId}&Tip={Tip}&Email={Email}&TxId={TxId}");
//var pphereUrl = "paypalhere://takePayment/?returnUrl={{returnUrl}}&invoice=%7B%22merchantEmail%22%3A%22{{merchantEmails}}%22,%22payerEmail%22%3A%22{{payerEmails}}%22,%22itemList%22%3A%7B%22item%22%3A%5B%7B%22name%22%3A%22{{name}}%22,%22description%22%3A%22{{description}}%22,%22quantity%22%3A%221.0%22,%22unitPrice%22%3A%22{{price}}%22,%22taxName%22%3A%22Tax%22,%22taxRate%22%3A%220.0%22%7D%5D%7D,%22currencyCode%22%3A%22{{currency}}%22,%22paymentTerms%22%3A%22DueOnReceipt%22,%22discountPercent%22%3A%220.0%22%7D";
var pphereUrl = "paypalhere://takePayment/v2?returnUrl=" + retUrl;
pphereUrl = pphereUrl + "&accepted=cash,card,paypal";
pphereUrl = pphereUrl + "&step=choosePayment";
pphereUrl = pphereUrl + '&invoice=' + escape(JSON.stringify(invoice));
console.log(pphereUrl);
return pphereUrl;
}
$scope.pay = function () {
var url = onPay();
window.open(url, "_system");
}
}]);
detail.html
<ion-header-bar class="bar-dark">
<h2 class="title">Order Detail</h1>
</ion-header-bar>
<ion-view>
<ion-content class="has-subheader">
<ion-list class="list-inset">
<ion-item class="item-text-wrap"
ng-repeat="order in orders | filter: { bkor_user: whichorder }">
<h1>Production Name: {{order.bkev_name}}</h1>
<h3>Seatcount: {{order.bkor_seatcount}}</h3>
<h1>Order Subtotal: £{{order.bkor_subtotal}}</h1>
</ion-item>
<button class="button button-block button-dark" ng-click="pay();">Pay Here</button>
</ion-list>
</ion-content>
</ion-view>
JSON data
[
{
"bkor_status": "A",
"bkor_datedmy": "08-02-2016",
"bkor_event": "34",
"bkor_user": "4028",
"bkev_name": "U2 Tribute",
"bkor_seatcount": "5",
"bkor_paymethod": "H",
"bkpay_short": "Cash",
"bkpay_status": "A",
"bkor_paid": "Y",
"bkor_payamount": "44.00",
"bkor_paiddatedmy": "08-02-2016",
"bkor_delivery": "N",
"bkdel_short": "Given",
"bkor_sent": "N",
"bkor_sentdatedmy": null,
"bkor_subtotal": "44.00",
"bkor_bookingfee": "0.00",
"estCardFee": "2.00",
"bkor_handling": "0.00",
"bkor_discount": "0.00",
"bkor_adjustment": "0.00"
},
{
"bkor_status": "A",
"bkor_datedmy": "16-02-2016",
"bkor_event": "35",
"bkor_user": "5001",
"bkev_name": "Fleetwood Mac Tribute",
"bkor_seatcount": "3",
"bkor_paymethod": "H",
"bkpay_short": "Card",
"bkpay_status": "A",
"bkor_paid": "Y",
"bkor_payamount": "28.00",
"bkor_paiddatedmy": "08-02-2016",
"bkor_delivery": "N",
"bkdel_short": "Given",
"bkor_sent": "N",
"bkor_sentdatedmy": null,
"bkor_subtotal": "28.00",
"bkor_bookingfee": "0.00",
"estCardFee": "2.00",
"bkor_handling": "0.00",
"bkor_discount": "0.00",
"bkor_adjustment": "0.00"
}
]
Move the button inside the ng-repeat loop and pass the order to your pay() scope function and then you can pass it to onPay() and not use the hardcoded var order = $scope.orders[0];
HTML
<ion-item class="item-text-wrap"
ng-repeat="order in orders | filter: { bkor_user: whichorder }">
<h1>Production Name: {{order.bkev_name}}</h1>
<h3>Seatcount: {{order.bkor_seatcount}}</h3>
<h1>Order Subtotal: £{{order.bkor_subtotal}}</h1>
<button class="button button-block button-dark" ng-click="pay(order);">Pay Here</button> <-- move this here and pass 'order'
</ion-item>
Controller
function onPay(order) {
var itemsArr = [];
var invoice = {};
var myItems = {};
var myItem = {};
// var order = $scope.orders[0]; <-- remove this
[ ... ]
}
$scope.pay = function (order) {
var url = onPay(order); <-- pass order
window.open(url, "_system");
}

Angular: Not able to reach method from scope

I'm trying to use method from my $scope controller, imported from Factory and execute it on onlick method in Ionic based HTML.
I am still getting undefined and I don't know why, because any other variables from $scope are available (like userid). Is this scope hierarchy problem? I read through many articles, but I'm still stuck. Thanks.
Controller:
var mod = angular.module('Baybee.controller.nameList', []);
mod.controller('NameListCtrl', function ($scope, AllNamesList, UidGenerator, $localstorage) {
//importing list of names from Factory and unique user-id
$scope.namesFromService = AllNamesList.getList('AllNamesList');
$scope.userid = UidGenerator;
// test functions which I wasn't able to execute on 'onclick' method. scope.saveName should be that I wanted to use originaly
$scope.saveName = AllNamesList.transferName;
$scope.testb = function () {
console.log('working!');
};
});
Factory:
var mod = angular.module('Baybee.factory.allNamesList',['ionic'])
.factory('AllNamesList', function($localstorage) {
// 3 more list available as variables, here is just one
var AllNamesList = {
names: [
{
"name": "Jakub",
"set": [
"CzechCalendar",
"Top10Cz2015",
"Top50Cz2010"
],
"properties": {
"sex": "male",
"origin": "Hebrew",
"description": "Comes from Hebrew, יַעֲקֹב (Yaʿqob, Yaʿaqov, Yaʿăqōḇ)"
},
"popularity": [
{
"Cz": {
"2011": "10",
"2012": "7",
"2013": "6",
"2014": "6",
"2015": "7"
}
}
]
}
// more names here
]
};
return {
// returns right list with names based on string argument
getList: function(a) {
switch (a) {
case "AllNamesList":
return AllNamesList;
break;
case "loveNameList":
return loveNameList;
break;
case "maybeNameList":
return maybeNameList;
break;
case "noGoNameList":
return noGoNameList;
break;
default:
console.log("Sorry, can't find list with names");
}
},
// I would like to use this function on onlick method to transfer object with name properties to the right list (
transferName: function(name, listFrom, listTo){
// saving both list names into local memory
for (i = 0; i < listFrom.length; i++) {
if (name = listFrom[i]) {
listTo.push(listFrom[i]);
console.log(listFrom);
listFrom.splice(i, 1);
console.log(listTo);
}
else {
console.log('Cannot find: ' + name + ' in ' + listFrom);
}
}
}
}
});
HTML Body:
<body ng-app="baybee">
<ion-pane ng-controller="NameListCtrl">
<ion-header-bar class="bar-energized" >
<h1 class="title" >Baybee</h1 >
</ion-header-bar >
<ion-content >
<ion-list >
<div ng-repeat="names in namesFromService track by $index">
<ion-item ng-repeat="(key, value) in names"
on-swipe-right=""
on-swipe-left=""
//I would like to execute any function from scope here, but Im getting undefined
//onclick="testb()"
//onclick="saveName(name, 'list1', 'list2')"
<h2>{{value.name}}</h2>
<p>{{value.properties.origin}}</p>
</ion-item>
</div>
</ion-list >
</ion-content >
</ion-pane >
</body >
There is mistake in HTML part, I use onclick method, when it should be ng-click.
ng-click="saveName(name, 'list1', 'list2')"
Thanks

Sending specific data to json file from angularJS app using PHP

I have a Library angularJS application and a JSON Data file that contains an array of book's information like this
[
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
},
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
}
]
"current" is for the current page of the current book that i'm reading
and there is a "next" and "prev" buttons in the reading view
when i press "next" it adds "+1" to the "current" num page
the question is (How to send this +1 to the "current" in JSON file with PHP?)
I have this PHP code :
<?php
$jsonString = file_get_contents('library.json');
$data = json_decode($jsonString, true);
$data[0]['current'] = 3;
$newJsonString = json_encode($data);
file_put_contents('library.json', $newJsonString);
?>
See the ($data[0]) is for the index of the first book, how do i send to PHP the index of the current book so it updates the "current" data of the current book?
Here is the "next" function :
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php")
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
And here is the reading Controller :
app.controller('read', ['$scope','books', '$routeParams',function($scope,books, $routeParams) {
books.success(function(data){
$scope.book = data[$routeParams.bookId]
$scope.pdfUrl = data[$routeParams.bookId].bookUrl;
$scope.pdfName = data[$routeParams.bookId].name;
});
//the pdf viewer options
//$scope.pdfUrl = 'data/tohfa12.pdf';
$scope.scroll = 0;
$scope.loading = 'Loading file please wait';
$scope.getNavStyle = function(scroll) {
if(scroll > 100) {
return 'pdf-controls fixed';
} else {
return 'pdf-controls';
}
};
$scope.onError = function(error) {
console.log(error);
};
$scope.onLoad = function() {
$scope.loading = '';
};
$scope.onProgress = function(progress) {
console.log(progress);
};
$scope.currentBookIndex = parseInt($routeParams.bookId);
}]);
I know it's complicated but i really need that , thanks.
How do you expect your application to behave?
You need to send the bookId and the pageNum with your request!
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php", {
param : {
bookId: $scope.bookId,
pageNum: $scope.pageNum
}
})
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
BTW. By REST design a GET http request should never change a resource. GET is for READING. If you want to update a resource you should use POST, PUT or DELETE

How to update model using angularjs, Django,Django rest framework

I have such json representation of a post by its id:
http://127.0.0.1:8000/update/1?format=json
{"title": "about me", "content": "I like program", "created": "2014-11-29T18:07:18.173Z", "rating": 1, "id": 1}
I try to update rating by button click:
<button ng-click="click(post.id)">Click me</button>
I have such javascript code:
<script>
var demoApp = angular.module('demoApp',['ngResource']);
demoApp.controller( 'AllPosts', function ($scope, $http)
{
$http.get('/blogpost/?format=json').success(function(data,status,headers,config)
{
$scope.posts = data.results;
$scope.predicate = '-title';
$scope.click = function(post_id, $resource){
var Post = $resource('/update/:PostId ',{PostId:post_id,format:'json'} );
post = Post.get({PostId:post_id}, function() {
post.rating = post.rating+ 1 ;
post.$save();
});
};
}).error(function(data,status,headers,config)
{} )
;})
</script>
Peharps i have mistake because in json i have a single object. But i dont really know
Besides i have such view to have a json by certain post by its id:
class UpdateModel(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'id'
queryset = BlogPost.objects.all()
serializer_class = BlogPostSerializer
permission_classes = (AllowAny,)
A quick tidy up of your script tag shows that you are only defining the function click if the http call was successful.
I would suggest moving the definition of the click method outside of the success callback.
You may also be running into a race condition that the click function has not been defined before clicking the actual button. Regardless you will want to move that function definition to where the controller is actually created.
Suggested edits (moved click definition outside of http call response):
var demoApp = angular.module('demoApp', ['ngResource']);
demoApp.controller('AllPosts', function($scope, $http, $resource) {
$scope.click = function(post_id) {
var Post = $resource('/update/:PostId ', {
PostId: post_id,
salutation: 'json'
});
post = Post.get({
PostId: post_id
}, function() {
post.rating = post.rating + 1;
post.$save();
});
};
$http.get('/blogpost/?format=json').success(function(data, status, headers, config) {
$scope.posts = data.results;
$scope.predicate = '-title';
}).error(function(data, status, headers, config) {});
})
Updates:
Injected $resource into the controller
Removed $resource from click function params

Categories