I need to create a list of clickable radio buttons that gets generated through an ajax request. They will look like this:
10/15/2018
10/14/2018
10/13/2018
....
So I am doing the Ajax call below and getting the result:
onTabChange: function (tabPanel, tab) {
if (tab.getTitle() == 'Reconciliation') {
Ext.Ajax.request({
url: '***',
reader: {
type: 'json',
rootProperty: 'data'
},
useDefaultXhrHeader: false,
withCredentials: true,
scope: this,
success: function (response) {
var selectReconciliation = this.lookupReference('lisatradereconciliation');
// Get the data from Ajax Request and shape it
var data = Ext.JSON.decode(response.responseText).data;
var reconciliationItems = [];
// Put the data into a shape that it will need to look like on the page
for (var i in data) {
reconciliationItems.push("boxLabel: '" + data[i].substr(5, 2) + "/" + data[i].substr(8, 2) + "/" + data[i].substr(0, 4) +"', name: 'rI', inputValue: 'data[i]'");
}
},
failure: function (response) {
'***'
}
});
}
},
Which then I am sending it to the view radiogroup item as follows:
items: [{
xtype: 'radiogroup',
fieldLabel: 'day',
items: reconciliationItems
}]
But this doesn't work.
The reconciliationItems array should be defined as a global variable, or outside of your ajax success handler, to achieve what you want:
Define the array outside of success:
window.reconciliationItems = [];
And then access it in the success handler like so:
success: function (response) {
var selectReconciliation = this.lookupReference('lisatradereconciliation');
// Get the data from Ajax Request and shape it
var data = Ext.JSON.decode(response.responseText).data;
// var reconciliationItems = []; <-- Dont define here
// Put the data into a shape that it will need to look like on the page
for (var i in data) {
reconciliationItems.push("boxLabel: '" + data[i].substr(5, 2) + "/" + data[i].substr(8, 2) + "/" + data[i].substr(0, 4) +"', name: 'rI', inputValue: 'data[i]'");
}
},
Related
i have a angularJS controller where i put a kendo cascade dropdownlist.For dropdown list value ,on kendo dataSource read i am calling the web api service.
For the first field the api GetDivisions() has been called and it response also but for the 2nd value the GetCascadeDistrict() method not called the GetDivisions() method called again. How can i solve this.Need Help
here's the angular Controller with kendo cascade dropdownlist.
app.controller("filterCtrl", function($scope, $sce,$http) {
var i;
$scope.dashImgSrc = $sce.trustAsResourceUrl('Content/Images/Bangladesh_Govt.gif');
$(document).ready(function () {
var divisions = $("#divisions").kendoComboBox({
filter: "contains",
placeholder: "select a divisions...",
dataTextField: "Name",
dataValueField: "Id",
animation: {
close: {
effects: "zoom:out",
durations:250
}
},
dataSource: {
type: "json",
serverFiltering: true,
transport: {
read: "api/AreaService/GetDivisions()"
}
},
change: function () {
i = divisions.value();
alert("1st hit"+i);
}
}).data("kendoComboBox");
var districts = $("#districts").kendoComboBox({
autoBind: false,
cascadeFrom: "divisions",
filter: "contains",
placeholder: "select a district",
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
type: "json",
serverFiltering: true,
transport: {
read: function () {
alert("2nd hit");
//$http.get("/api/AreaService/GetCascadeDistrict(i)").success(function() {
// alert("Hit the district api");
//}).error(function() {
// alert("Error");
//});
$http({ method: "GET", url: 'api/AreaService/GetCascadeDistrict(i)' }).
success(function() {
alert("Actually it hit the custome get method");
}).
error(function() {
alert("Not hit or other problem");
});
}
}
}
}).data("kendoComboBox");
var upazila = $("#upazila").kendoComboBox({
autoBind: false,
cascadeFrom: "districts",
filter: "contains",
placeholder: "select a upazila...",
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
type: "json",
serverFiltering: true,
transport: {
read: function() {
$http.get("/api/AreaService/GetCascadeDistrict(i)").success(function() {
}).error(function() {
});
}
}
}
}).data("kendoComboBox");
$("#get").click(function () {
var divisionInfo = "\Division: { id: " + divisions.value() + ", name: " + divisions.text() + " }",
districtInfo = "\nDistrict: { id: " + districts.value() + ", name: " + districts.text() + " }",
upazilaInfo = "\nUpazila: { id: " + upazila.value() + ", name: " + upazila.text() + " }";
alert("Road details:\n" + divisionInfo + districtInfo + upazilaInfo);
});
});
});
And the Web api is here
public class AreaServiceController : ApiController
{
private readonly AreaFilterManager _db = new AreaFilterManager();
[System.Web.Http.HttpGet]
public IEnumerable<Division> GetDivisions()
{
return _db.GetDivisions();
}
[System.Web.Http.HttpGet]
public IEnumerable<District> GetCascadeDistrict(int? division)
{
return _db.GetCascadeDistrict(division);
}
[System.Web.Http.HttpGet]
public IEnumerable<Thana> GetCascadeUpzilla(int? district)
{
return _db.GetCascadeThana(district);
}
}
You'll need to separate/distinguish your calls by CRUD operations or by Attribute Routing depends your WebApi version your using in your project.
You cannot use the same CRUD HttpGet twice in the same Class/Controller without putting a different routing attribute.
You need to remember, in WebApi the methods are not being called by their names like in regular programming, therefore the WebApi Class/Controller doesn't know which method you meant to call from your Client (in your case).
That's why you'll need to:
WebApi Ver 1 : separate/distinguish your calls by CRUD operations.
WebApi Ver 2 : separate/distinguish your calls by Attribute Routing.
I have created custom select2 directive for angular it works perfect for my usecase and works like charm when i use template and it sets and get the values from input/ngModel
but when i use it on view page it do not resolve ngModel via scope.$eval
this is something scope issue please help me on this
please find directive mentioned below:
(function () {
'use strict';
var directiveId = 'snSelect2';
angular.module('app').directive(directiveId, ['datacontext', snSelect2]);
function snSelect2(datacontext) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, controller) {
var urlPrefix =datacontext.urlPrefix;
$(function () {
element.select2({
placeholder: element.attr('placeholder'),
multiple: angular.isDefined(attrs.multiple),
minimumInputLength: 3,
blurOnChange: true,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: urlPrefix + "/Employees",
dataType: 'json',
data: function (term) {
return {
term: term
};
},
results: function (data) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return { results: data };
}
},
initSelection: function (element, callback) {
var id = scope.$eval(attrs.ngModel);//$(element).val();
if (id != "") {
$.ajax(urlPrefix + "/EmployeeById",
{
data: {
id: id,
format: 'json'
},
datatype: 'json'
}).done(function (data) {
if (angular.isDefined(attrs.multiple)) {
callback(data);
}
else {
callback(data[0]);
}
});
}
//var data = {id: element.val(), text: element.val()};
//callback(data);
},
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
}).select2('val', scope.$eval(attrs.ngModel))
.on("change", function (e) {
scope.$apply(function () {
controller.$setViewValue(attrs.ngModel);
});
});
element.bind("change", function (e) {
scope.$apply(function () {
scope[attrs.ngModel] = e.val;
});
});
});
}
}
}})();
http://snag.gy/lcizI.jpg
<!-- html element -->
<input type="hidden" class="form-control" data-ng-model="show" ui-select2="getShow">
$scope.getShow = {
placeholder: "Enter Show Code",
minimumInputLength: 3,
escapeMarkup: function (m) { return m; },
formatSelection: function(obj, container) {
return "ID: " + obj.showid + " - " + obj.name;
},
formatResult: function(obj, container, query) {
var start = obj.startdate ? moment(obj.startdate).format("DD/MM/YYYY") : "Unknown";
var end = obj.enddate ? moment(obj.enddate).format("DD/MM/YYYY") : "Unknown";
return '<div class="list-group-item small">' +
'<i><span class="label label-default pull-right">ID: ' + obj.showid + '</span></i>' +
'<i><span class="label label-info">(' + obj.code + ')</span></i>' +
'<div style="padding-top: 4px"><strong>' + obj.name + '</strong></div>' +
'<i>' + start + " - " + end + '</i>' +
'</div>';
},
query: function(options) {
if (!options.context)
options.context = {};
// status == processing means http request is in process, so don't do it again
if (options.context.status === "processing")
return;
options.context.status = "processing";
// this is just like ajax $http.get("/search").
model.show.search("search", {code: options.term, limit: 10, sort: 'ts desc'} )
.then(function(result) {
// set status = completed to indicate http request finished.
options.context.status = "completed";
// when you get the result from ajax, callback require you to call with
// an object { results: your result } as result
$scope.list.datalist.show = result;
options.callback({
results: result
});
});
}
}
Data from server looks like
[{
code: "MELCCS"
enddate: "2014-03-10T14:00:00.000Z"
id: "5329c28087b375a4d8a2af43"
name: "Melbourne Caravan and Camping Show"
openinghour: ""
showid: 1810
startdate: "2014-03-05T14:00:00.000Z"
state: "VIC"
status: "Research"
ts: 1395245779280
updatedAt: "2014-03-21T09:16:56.859Z"
warehouse: "52ecd53b673a5fba428e21a7"
}]
With Rally SDK 2.0 APIs, I want to associate new TestCases to a given TestSet. To do this I :
initialize a store:
me.selectedTestCasesStore = myTestSet.getCollection('TestCases',{...});
Remove all items (I don't want to keep them):
me.selectedTestCasesStore.removeAll();
Add the new TestCases
me.selectedTestCasesStore.add({'_ref':aTestCaseRecord.data._ref});
Then synchronize
me.selectedTestCasesStore.sync({...});
Step 1 is OK : console.log(me.selectedTestCasesStore) shows me the collection in data.items[].
Step 2 seems OK as a console.log(me.selectedTestCasesStore) shows me nothing in data.items[] (previous records are gone).
Step 3 is OK because added test cases which were not present at step 1 are now in the collection
Step 4 : Called function is "success"
BUT... only new TestCases are added, the old ones are not removed, as if step 2 has no effect. What's wrong in my code ? I extract the part of the concerned code :
// me.selectedTestCasesStore : my store, with old TestCase associated to a TestSet.
// It is initialized with something like :
// me.selectedTestCasesStore = myTestSet.getCollection('TestCases',{...});
//
// selectedTestCasesArray : an array of records with the new TestCases to assign to the test set.
_removeAllFromSelectedTestCaseStore:function()
{
var me = this ;
console.log('In _removeAllFromSelectedTestCaseStore');
me.selectedTestCasesStore.addListener({
clear : me._addSelectedTestCasesToSelectedTestCaseStore,
scope : me,
});
// Remove all associated TestCases from selectedTestCases store
me.selectedTestCasesStore.removeAll();
},
_addSelectedTestCasesToSelectedTestCaseStore:function()
{
var me = this ;
console.log('In _addSelectedTestCasesToSelectedTestCaseStore');
console.log(' After remove, store is now :',me.selectedTestCasesStore);
// Add each check TestCase to selectedTestCases store
for (var i=0; i < me.selectedTestCasesArray.length; i++)
{
// Add it to the collection
me.selectedTestCasesStore.add({'_ref':me.selectedTestCasesArray[j].data._ref});
}
console.log(' After add, store is now :',me.selectedTestCasesStore);
// Synchronyze
me.selectedTestCasesStore.sync(
{
success: function(batch, options) {
//success!
console.log(' Success', me.selectedTestSetStore);
},
failure: function(batch, options){
console.log(' Faillure :(', me.selectedTestSetStore);
},
});
},
Thanks for your help !
This works for me instead of removeAll():
var testcases = testCaseStore.getRange();
_.each(testcases, function(testcase) {
testCaseStore.remove(testcase);
});
Here is the full js file that empties the test case collection on a test set before adding a new test case
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
console.log("launch");
Rally.data.ModelFactory.getModel({
type: 'TestSet',
success: this._onModelRetrieved,
scope: this
});
},
_onModelRetrieved: function(model) {
console.log("_onModelRetrieved");
this.model = model;
this._readRecord(model);
},
_readRecord: function(model) {
var id = 16805375409;
console.log("_readRecord");
this.model.load(id, {
fetch: ['Name', 'FormattedID', 'TestCases'],
callback: this._onRecordRead,
scope: this
});
},
_onRecordRead: function(record, operation) {
console.log('name:', record.get('Name'));
console.log('test cases:', record.get('TestCases'));
if(operation.wasSuccessful()) {
var testCaseStore = record.getCollection('TestCases', {
autoLoad: true,
listeners: { load: function() {
var testcases = testCaseStore.getRange();
_.each(testcases, function(testcase) {
testCaseStore.remove(testcase);
});
testCaseStore.sync({
callback: function() {
console.log('test cases after removeAll():', record.get('TestCases'));
}
});
testCaseStore.add({'_ref':'/testcase/14469886070'});
testCaseStore.sync({
callback: function() {
console.log('test cases after add():', record.get('TestCases'));
}
});
}}
});
}
},
});
I am trying to populate instagram images using backbone,
I have basically 3 models as follows,
User model store all the user info related to instagram
App.Models.User = Backbone.Model.extend({
defaults: {
id: '',
access_token: '',
userid: '',
username: '',
full_name: '',
profile_picture: ''
},
urlRoot: "/api/user/",
initurl: function() {
return "https://api.instagram.com/v1/users/"+this.get('userid')+"/media/recent/?access_token=" + this.get('access_token');
},
initialize: function() {
this.set('id', $('#domdump .id').val());
this.fetch({
success: function(model) {
var photos = new App.Collections.Ig_photos([],{
url: model.initurl()
});
}
});
}
});
A model to store the next url for pagination
App.Models.Ig_next_url = Backbone.Model.extend({
defaults: {
next_url: ''
},
next_url:function(){
return this.get('next_url');
}
});
A model for the photo
App.Models.Ig_photo = Backbone.Model.extend({});
A collection for the multiple photo
App.Collections.Ig_photos = Backbone.Collection.extend({
model: App.Models.Ig_photo,
initialize: function(model, options) {
this.url = options.url;
this.nextSet();
},
sync: sync_jsonp,
parse: function( response ) {
if(response.pagination && response.pagination.next_url && response.pagination.next_url != this.url){
var next_url = new App.Models.Ig_next_url({ next_url: response.pagination.next_url });
this.url = next_url.next_url();
}
return response.data;
},
nextSet: function(){
this.fetch({
success: function(photos){
var ig_photos_views = new App.Views.Ig_photos_view({ collection: photos});
console.log(photos);
}
});
}
});
Also i have some views that does the render with a load more button that calls the nextset of the collection.
What i was trying to achieve is the photos get appended to the collection upon nextset() and the collection get updated with pervious data + new data but right now its getting overwritten.
Also is it okay to instantiate new collection from the modelfetch ?
You shouldn't need to make a new view. You should instead listen to the "add" event being triggered on the collection and render new items accordingly.
nextSet: function(){
this.fetch({add : true}); // The add option appends to the collection
}
This option is detailed in the very good documentation.
I have a model that looks like this:
var TodosModel = Backbone.Model.extend({
defaults: {
id: null,
content: 'Something Todo',
completed: false
},
url: function() { return 'api/'+this.id; }
});
I'm adding models via:
var todoID = _.uniqueId();
var todoContent = this.newTodoField.val();
var todoCompleted = false;
// Ensure there's something to save
if(todoContent.length>0){
var _this = this;
// Create model
var todo = new TodosModel({
id: todoID,
content: todoContent,
completed: todoCompleted
});
todo.save({}, {
wait: true,
success: function(model, response) {
// Let the events deal with rendering...
_this.collection.add(model);
},
error: function(model, response) {
console.log('Could not create todo');
}
});
}
The problem I'm having is that for some reason every id is double incremented - so if I start with no elements I get 1,3,5,7...
Which holds alright, except if I reload and those ID's are brought in from the API, and then the next generated _.uniqueID is based on the count rendered out.
Any help would be greatly appreciated, here's the full code: http://sandbox.fluidbyte.org/todos/js/todos.js