simple Previous/Next buttons - javascript

I'm triying to paginate the response of an API. This API, have 15 items per page.
Actualy, i'm using something like this:
vm.next = function(currentPage){
$http.get('/api?page='+vm.firstPage++)
.then(function(data){
vm.chuck = data.data.Response;
});
}
vm.previous = function(currentPage){
$http.get('/api?page='+vm.firstPage--)
.then(function(data){
vm.chuck = data.data.Response;
});
}
and
vm.firstPage = 1;
My html view for buttons:
<div class="text-center">
<button type="button" class="btn btn-warning" ng-click="$ctrl.previous()">Previous</button>
<button type="button" class="btn btn-warning" ng-click="$ctrl.next()">Next</button>
</div>
The idea was to had the increment/decrement on every click. It works, but only after the second click. Also, if i change the value of vm.firstPage to 2, it works since the very first click, but when i click Previous, it becomes a mess.
What can i do to have the increment/decrement on the buttons?
I'm using AngularJs and javascript

I think it's about the operator precedence. Make vm.firstPage++/vm.firstPage-- before API call
vm.next = function(currentPage){
vm.firstPage++;
$http.get('/api?page='+vm.firstPage)
.then(function(data){
vm.chuck = data.data.Response;
});
}

Related

How can I target a button within a temperate literal, for use in a separate click function?

Currently, Im using temperate literals to generate buttons to go along with locally stored data per result. This data is generated via a click which handles calling the storage to get back the information, displaying it a container. However, when I want to target the button, it's unresponsive.
My code
$(document).ready(() => {
const genMonthlyQueueBtn = $("#genMonthlyQueue");
const genTransientQueueBtn = $("#genTransientQueue");
const monthlyPlateQueue = () => {
const $insertMonthly = $('#insertMonthlyPlates');
$insertMonthly.empty();
let monthlyPlates = JSON.parse(localStorage.getItem('Monthly Plates'));
for (i = 0; i < monthlyPlates.length; i++) {
console.log(monthlyPlates);
$insertMonthly.append(`
<div class="container" id="generatedMonthlyPlates">
<input type="text" width="100px" name="monthlyLicensePlate" id="monthlyLicensePlate" class="licensePlate" placeholder="AB12345" value=${monthlyPlates[i]}/>
<div class="text-center">
<button class="btn btn-warning" type="submit" id="editMonthlyPlate" name="action">Edit
<i class="material-icons right">edit</i>
</button>
<button class="btn btn-danger" type="submit" id="deletePlate" name="action">Delete
<i class="material-icons right">delete</i>
</button>
</div>
</div>
`)
}
}
// get the array from local storage through queue function
genMonthlyQueueBtn.click(() => {
monthlyPlateQueue();
})
// call generated button and test functionality to edit and push back to storage
const editMonthlyPlateBtn = $('#editMonthlyPlate');
const editMonthlyPlate = () => {
console.log('I was clicked');
}
editMonthlyPlateBtn.click(() => {
editMonthlyPlate();
})
Is there a better way to do this? or am I going about it the wrong way?
This data is triggered with a previous button click, and when adding an onClick function to the button itself, It's just called every time I generate the list and not when I clicked the button itself which is expected but not what I need.

AngularJS - how to not display HTML element until the variable it is binded to is loaded in the JS?

This is my HTML:
<button type="button" class="btn btn-primary" ng-hide="ctrl.userProfile.following">Follow</button>
<button type="button" class="btn btn-primary" ng-show="ctrl.userProfile.following">Unfollow</button>
So basically, I want to hide the "Follow" button and show the "Unfollow" button if ctrl.userProfile.following is true, and vise-versa.
This is my back-end:
self.userProfile = {};
function fetchUserProfile() {
$http.get('/users/' + username)
.then(function(response) {
self.userProfile = response.data;
}, function(response) {
self.cerrorMessages = BaseService.accessErrors(response.data);
});
};
fetchUserProfile();
So I get the userProfile and then update self.userProfile with the watching variable (this occurs when I do self.userProfile = response.data. With that said, is there a way for me to tell HTML to not display the buttons until self.userProfile is filled with watching variable?
Create a userProfile.ready flag and use that to control the showing of the Follow and Unfollow buttons.
HTML
<div ng-show="ctrl.userProfile.ready">
<button type="button" ng-hide="ctrl.userProfile.following">Follow</button>
<button type="button" ng-show="ctrl.userProfile.following">Unfollow</button>
</div>
JS
self.userProfile = {};
self.userProfile.ready = false;
function fetchUserProfile() {
self.userProfile.ready = false;
$http.get('/users/' + username)
.then(function(response) {
self.userProfile = response.data;
self.userProfile.ready = true;
}, function(error) {
self.cerrorMessages = BaseService.accessErrors(error.data);
});
};
fetchUserProfile();
There are a few ways of doing this. Here is one:
If you start with an empty object, and are waiting for the promise to resolve, you can set a scope variable that checks the length of the object.
e.g.
self.userProfileLength = Object.keys(self.userProfile).length;
And in the view, do: ng-if="ctrl.userProfileLength"
(Note: Or use ng-show if you want to keep the element in the DOM)
Object.keys returns the keys from the object in an array. Anything over a length of 0 is a truthy value so it will pass the ng-if condition.

Add Friend with Ajax - Django

I'm using Django-Friends
I'm trying to have it so when a user clicks on the add friend, the button disappears(or ideally says Request sent). However, when I click the button, it doesn't disappears. I am new at Django and Ajax, so I'm assuming that this is an error on my part. Most likely the HttpResponse.
That part actually confuses me a lot. The HttpResponse, render, render_to_response, etc. I know that I can use render or render_to_response when I want to load a template. But what if I don't want to load up a new template or go to a new page? Like I want to be able to complete an action like add a friend, or add a page, etc; all on one page. I know you can use ajax to do it, but I don't know the django technical aspect of it.
Anyway, here's my code. Right now, nothing happens. The button doesn't disappear, and there is no friendships request sent.
profile.html
<div class="text-center">
<div>
"{{currUserprofile.tagline}}"
</div>
{{currUser.profile.city}}, {{currUser.profile.state}}
{{currUser.id}}
</div>
<!-- <button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
--> <!--Find a way to signify looking or not looking to mentor -->
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
ajax.js
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
})
views.py
#login_required
def profile(request, id):
context = RequestContext(request)
currUser = User.objects.get(pk = id)
profile = UserProfile.objects.filter(user = currUser)
return render_to_response('myapp/profile.html', {'currUser': currUser, 'UserProfile': UserProfile}, context)
#login_required
def addfriend(request, id):
context = RequestContext(request)
other_user = User.objects.get(pk=id)
new_relationship = Friend.objects.add_friend(request.user, other_user)
profile = UserProfile.objects.filter(user = other_user)
return HttpResponse(new_relationship)
Here is a working JSFiddle, but you can't post data {profile_id: profile_id}with a getyou should use a postor add the data as params, as I did:
HTML:
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
JS:
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/?profile_id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
});

Save items from controller into array on Yes / No basis

Having some trouble with angularJS i've only been working with it for two weeks and my javascript knowledge aswell is rather no existent so please take this into account.
Im currently making a hearing test app which all functionality is working apart from a reporting system im building into it.
Im wanting on a yes / no basis record at what frequency and DB they heard the sound from these two buttons.
<button ng-click='' type="button" class="btn btn-primary btn-lg glyphicon glyphicon-ok"></button>
<button ng-click='' type="button" class="btn btn-default btn-lg glyphicon glyphicon-remove"></button>
Here is an example of one of my controllers for 125HZ at 0DB as an example.
// 125 FREQUENCY START
myApp.controller('125Zero', ['$scope','ngAudio', function($scope, ngAudio) {
$scope.title = "Frequency: 125Hz";
$scope.frequency = "0Db";
$scope.sound = ngAudio.load("audio/125_0.mp3"); // returns NgAudioObject
$scope.previous =""
$scope.next ="125Ten"
}]);
Im wishing to record the $scope.title and $scope.frequency attribute into and array for later processing.
this is as far as ive got with the idea
function result() {
$scope.results = [];
$scope.resultService = function(){
$scope.results.push();
}
}
with no results, i want to save both title and frequency into the array, and allow the program to move onto the next controller and do the same if the frequency is heard.
Thanks for any help or ideas.
Apologies if my code isn't the cleanest or ideal but as i explained this is my second week working with AngularJS
Thanks.
Add event listeners to the buttons:
<button ng-click='buttonPressed('okay")' type="button" class="btn btn-primary btn-lg glyphicon glyphicon-ok"></button>
<button ng-click='buttonPressed("remove")' type="button" class="btn btn-default btn-lg glyphicon glyphicon-remove"></button>
In your controller, add those methods:
myApp.controller('125Zero', ['$scope','ngAudio', function($scope, ngAudio) {
$scope.title = "Frequency: 125Hz";
$scope.frequency = "0Db";
$scope.sound = ngAudio.load("audio/125_0.mp3"); // returns NgAudioObject
$scope.previous ="";
$scope.next ="125Ten";
$scope.buttonPressed= function(outcome) {
$scope.result = [];
var tempObj = {};
tempObj.title = $scope.title;
tempObj.frequency = $scope.frequency;
// check for outcome to find out if it's okay or remove.
//based on that set the frequency here.
$scope.result.push(tempObj);
// add this to service
}
}]);
To get this value in next controller:
You need to store that $scope.result inside a service. So create a service and push the $scope.result into that.
In your second controller, inject that service as a dependency and access the value there.

twitter bootstrap modal -- how to pass data to callback function

is there a way to pass additional data to bootstrap modal function callback?
for example, lets say my link that causes the modal to open has an extra attribute in it with a bit of useful data in it, how could I reference that attr?
HTML
<span listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
JS
$('#editTaskList').on('show', function () {
// get the source of the click, and then get the data i need.
});
Could this work for you ?
<span listid="80" href="#editTaskList" data-toggle="datamodal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
var $editTaskList = $('#editTaskList');
$('body').on('click.modal.data-api', '[data-toggle="datamodal"]', function (e) {
var $this = $(this);
$editTaskList.data('anyAttr',$this.data('anyAttr'));
$editTaskList.modal('show');
e.preventDefault();
})
$editTaskList.on('show', function () {
var myData = $editTaskList.data('anyAttr');
});
I know that this is an old question, but this is the first thing i've found on google. So, I want to put some important information here...
You NEED to put your callback function binded on events BEFORE you call the modal, for example:
$('#modal').on('shown', function(){
// Do something when the modal is loaded
});
$("#modal").modal();
This is very important and helped me a lot, so, here it is...
Like this -
<span id="modal_opener" data-extrastuff="stuff" listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
$('#modal_opener').click(function() {
var stuff_i_want = $(this).attr('data-extrastuff');
});

Categories

Resources