I have this in my html template. I want the button to fire the showMore function when clicked.
<button ng-click="showMore(secondPage)">Show More</button>
This is the controller. I'm not sure why $scope.nextPage will increment up everywhere except for at $scope.secondPage. I want $scope.secondPage to do fire on the first click Entry.query({page: 2}) then fire Entry.query({page: 3}) on the next click. But right now it keeps firing page 2.
#MainController = ["$scope", "Entry", ($scope, Entry) ->
$scope.entries = Entry.query({page: 1})
$scope.nextPage = 2
$scope.secondPage = Entry.query({page: $scope.nextPage})
$scope.showMore = (secondPage) ->
i = 0
while i < secondPage.length
$scope.entries.push(secondPage[i])
i++
$scope.nextPage++
console.log("nextpage" + $scope.nextPage)
]
I am using coffeescript. I don't fully understand why the page number in $scope.secondPage is not incrementing.
I'd do:
<button ng-click="showMore()">Show More</button>
#MainController = ["$scope", "Entry", ($scope, Entry) ->
$scope.entries = []
current_page = 1
$scope.showMore = ->
on_success = (entries)->
$scope.entries = $scope.entries.concat entries
current_page = current_page + 1
Entry.query {page: current_page}, on_success
$scope.showMore()
]
Related
I would like to know if it was possible to retrieve the attribute of a table in the same array. For example here I want to retrieve the "list.index" attribute of my array, how to do?
{
category_title = "Weapon",
description = nil,
type = "list",
list = {items = {"Give", "Remove"}, index = 1},
style = {},
action = {
onSelected = function()
if list.index == 1 then
-- it's 1
else
-- it's 2
end
end
},
It's not possible to use an entry in another entry when the table is being created.
But since you're defining a function, you can do this:
onSelected = function(self)
if self.list.index == 1 then
-- it's 1
else
-- it's 2
end
end
Just make sure you call onSelected with the table as an argument.
Alternatively, you may set the function after constructing the table in order to be able to access the table as an upvalue (as opposed to leveraging table constructors):
local self = {
categoryTitle = "Weapon",
description = nil,
type = "list",
list = {items = {"Give", "Remove"}, index = 1},
style = {},
action = {}
}
function self.action.onSelected()
if self.list.index == 1 then
-- it's 1
else
-- it's 2
end
end
That way, you get self as an upvalue and don't need to pass it as an argument.
I am using ajax with rails to get single random row I want to display just 10 rows with every request by ajax get one single random and display it, i try something like that, Model.all.sample or Using offset with first but my problem is duplication how can avoid it or how can i set all response to check if I sent it before or not Note: I send all elements was appended as array for backend to check if i send it before and change it but i have wrong
result
my code is :- in backend is my function
def get_10
arr = params['arr']
if arr.nil?
#rand_record = Phrase.all.sample
else
i = 0
if i < 10
#rand_record = Phrase.all.sample
while(i < arr.length) && (i<10)
flag = arr[i].include?#rand_record.name
if flag
#rand_record = Phrase.all.sample
i = 0
elsif flag == false
return #rand_record
end
i+=1
end
end
end
respond_to do |format|
format.js { }
end
end
in my js ajax is :
function myFunction(){
var arr = []
var len = $('li').length
for (let i=0 ; i< len; i++){
var attr = $('li')[i].childNodes['0'].data
arr.push(attr)
}
$.ajax({
method: 'GET',
url: '/phrase',
dataType: 'script',
data: {arr: arr}
}).done(function(data){
console.log(data);
})
}
in template is:
<div class="form-group">
<%= button_tag 'GetPhrases', type: 'button', onclick:"myFunction()", class: 'btn btn-default' , id:"get" %>
</div>
my result is
this pharase number 1
this pharase number 5
this pharase number 4
this pharase number 5
this pharase number 8
enter image description here
I want to avoid duplication I want to retrive just 10 random single row without duplication
Be careful with sample on the active record relation, instead do:
Model.where(id: Model.all.pluck(:id).sample(10))
This will just pluck all the IDs and sample 10 of them and then select records with those random 10 ids.
Consider the drag-and-drop sorting table implemented on http://benw.me. Table rows are moved - but when I restart the page, the location of the rows is not persisted, and reverts to the original.
Error query AJAX:
screenshot #1
update_row_order error 400
Controller:
def update_row_order
#task = Task.find(task_params[:task_id])
#task.row_order_position = task_params[:row_order_position]
#task.save
render nothing: true # this is a POST action, updates sent via AJAX, no view rendered
end
private
# Use callbacks to share common setup or constraints between actions.
def set_thing
#task = Task.find(params[:id])
end
Tasks.coffee:
jQuery ->
$('.best_in_place').best_in_place();
jQuery ->
if $('#sortable').length > 0
table_width = $('#sortable').width()
cells = $('.table').find('tr')[0].cells.length
desired_width = table_width / cells + 'px'
$('.table td').css('width', desired_width)
$('#sortable').sortable(
axis: 'y'
items: '.item'
cursor: 'move'
sort: (e, ui) ->
ui.item.addClass('active-item-shadow')
stop: (e, ui) ->
ui.item.removeClass('active-item-shadow')
# highlight the row on drop to indicate an update
ui.item.children('td').effect('highlight', {}, 1000)
update: (e, ui) ->
item_id = ui.item.data('item-id')
console.log(item_id)
position = ui.item.index() # this will not work with paginated items, as the index is zero on every page
$.ajax(
type: 'POST'
url: '/tasks/update_row_order'
dataType: 'json'
data: { thing: {task_id: item_id, row_order_position: position } }
)
)
Had the same problem, make sure to include :task_id in the tasks_params. So it should look like:
def task_params
params.require(:task).permit(:task_id, :other_params, :row_order_position, :other_param)
end
When I delete an object with #model.destroy method, it tries to redirect to the deleted object. How can I change the routing to redirect to root instead?
My delete method:
deleteBook: (ev) ->
#model.destroy success: ->
router.navigate "",
trigger: true
Router:
Router = Backbone.Router.extend(routes:
"": "home"
)
Update:
Full error:
GET http://localhost:3000/ 404 (Not Found) jquery.js?body=1:8707
send jquery.js?body=1:8707
jQuery.extend.ajax jquery.js?body=1:8137
Backbone.sync backbone_rails_sync.js?body=1:65
_.extend.destroy backbone.js?body=1:428
Backbone.View.extend.deleteBook main.js?body=1:32
jQuery.event.dispatch jquery.js?body=1:5096
elemData.handle
Update2:
My coffeescript file:
$(document).ready ->
window.Book = Backbone.Model.extend(
urlRoot: '/books/', idAttribute: 'id'
)
BooksView = Backbone.View.extend(
el: ".books"
addOne: (model) ->
view = new BookView(model: model)
$("ul.books").append view.render()
)
Router = Backbone.Router.extend(routes:
"": "home"
)
Books = Backbone.Collection.extend(
model: Book
url: '/books/'
)
BookView = Backbone.View.extend(
tagName: "li"
events:
"click .delete": "deleteBook"
deleteBook: (ev) ->
#model.destroy()
render: ->
##$el.append('Some text <button type="button" class="delete">Delete</button>')
title = #model.get("title")
author = #model.get("author")
year = #model.get("year")
link = "books/"+#model.get("id")
a = document.createElement('a')
a.href = link
show = 'Show'
row = title + ", " + author + ", " + year + " " + show
$(#el).html row
#$el.append(' <button type="button" class="delete">Delete</button>')
)
books = new Books()
books.url = "books.json"
books.fetch success: ->
books_view = new BooksView({})
_.each books.models, (model) ->
books_view.addOne model
It looks like it does not even look at the success function as, either it tries to redirect to the path were deleted object was.
Or maybe it still references deleted object and it tries to use GET method after delete somehow?..
Context: I have a Rails backend serving as an API to an Angular.JS front-end application.
Task: I want to retrieve all of the records of different species of "dinosaurs" from the Rails backend. Since there are over 500 records, I want to only get 30 species at a time.
My current approach: I am using the will_paginate gem in my Rails index controller action for the dinosaurs_controller. I have it running like this.
def index
#dinosaurs = Dinosaur.paginate(:page => params[:page], :per_page => 30)
end
In my Angular code:
I have a module called DinoApp and am using ngresource to create an Entry resource
app = angular.module("DinoApp", ["ngResource"])
app.factory "Entry", ["$resource", ($resource) ->
$resource("/api/v1/dinosaurs/:id", {id: "#id"}, {update: {method: "PUT"}} )
]
My Angular controller looks like this:
#MainController = ["$scope", "Entry", ($scope, Entry) ->
$scope.entries = Entry.query({page: 1})
$scope.viewPost = (dinosaurId) ->
]
This line of code would hit the API at dinosaurs_controller's index action and will only return 30 species of "dinosaurs" at a time:
$scope.entries = Entry.query({page: 1})
Now - how would I get angular.js to show a next page button and append the next page to the view?
I created a directive for this, which might be helpful:
https://github.com/heavysixer/angular-will-paginate
You can use a counter for the number of pages that gets incremented each time your controller gets called.
var counter = 1;
$scope.loadPage = function() {
$scope.entries = Entry.query({page: counter})
counter += 1 ;
}
And have a button that refer to that next page.
<button ng-click="loadPage()">Next page</button>