I am unable to get the AutoComplete list to display. My service returns json model: TagID: 1, text:MyText
but the AutoComplete list never displays. My HTML:
<tags-input ng-model="tags" tag-class="{even: $index % 2 == 0, odd: $index % 2 != 0}" on-tag-added="addTag(tags)"> <auto-complete source="loadTags($query)"></auto-complete> </tags-input>
My Controller code:
$scope.loadTags = function ($query) {
var tags;
contractorService.gettags()
.success(function (data) {
tags = data;
return tags.filter(function(tag) {
return tag.text.toLowerCase().indexOf($query.toLowerCase()) != -1
UPDATE
I have discovered that it just does not like the Json returned from Ajax call to MVC Controller.
public async Task<ActionResult> GetMajorTags()
{
majorId = UserInfo.intMajorID;
var tags = await CompanyClient.GetAvailableTags(majorId);
return Json(tags, JsonRequestBehavior.AllowGet);
}
Even bypassing the service and calling the MVC Controller method directly like below:
$scope.loadTags = function (query) {
return $http.get('/SSQV4/SSQV5/Contractor/GetMajorTags');
};
If I make the source static like below:
var auto = [
{ TagID: 4,text: 'Tag4' },
{ TagID: 5, text: 'Tag5' },
{ TagID: 6, text: 'Tag6' }
];
It works, but it will not show what is returned from the MVC Controller even though the data returned is in the EXACT same format.
Any assistance is greatly appreciated!
This code is not correct:
$scope.loadTags = function ($query) {
var tags;
contractorService.gettags()
.success(function (data) {
tags = data;
// return where?
return tags.filter(function(tag) {
return tag.text.toLowerCase().indexOf($query.toLowerCase()) != -1
});
});
}
There is no reason to have a return statement within your success callback. Where would that return to? If you did something like this:
var tags = $scope.loadTags();
console.log(tags); // undefined
... tags would be undefined. The reason is because the return statement is NOT returning from the call to loadTags. It is instead returning from within a promise callback.
This is actually how it's done:
var tags = [];
$scope.loadTags = function () {
contractorService
.gettags()
.success(function (data) {
tags = data;
tags = tags.filter(function(tag) {
return tag.text.toLowerCase().indexOf($query.toLowerCase()) != -1;
});
});
};
Notice how there are no return statements (except for your filter).
This just does not work at all:
$scope.loadTags = function (query) {
return $http.get('/SSQV4/SSQV5/Contractor/GetMajorTags');
};
If you were to do something like this:
var tags = $scope.loadTags();
console.log(tags); // promise object. NO DATA
tags would contain a promise object NOT your data. You would need to do the following to get the actual data:
var tags = [];
$scope.loadTags().success(function(data) {
tags = data;
});
I am trying to post from a HTML form to a Google sheet. I am currently just trying to write the code in the Google App script but an error states "Script function not found: doGet" and I cannot figure out what to do. My code is below:
function myFunction() {
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
}
Any help would be much appreciated.
You don't need to wrap the whole script in "myFunction()", if you remove that function with his corresponding bracket it should work just fine.
Remove this => function myFunction() { --from the beginning.
And this => } -- from the end.
You probably need to use ContentService
Google Documentation - Content Service
How to filter or sort info without data-attribute by plugin of MixItUp/Isototpe?
Maybe filter will be an #url and sort will be class.
Assuming you have a JSON set, you can filter against the values like so (I'm also assuming you have taken the filter/sort value from the DOM already):
Haven't run this so apologies if not exact - and I'm not used to stack overflow formatting yet but any issues and I'll edit. I think the logic should be OK
var dataset = [
{url: '/test'},
{url: '/test2'}
];
var filterValue = '/test2'; // pass this to function or get from DOM
var sortBy = 'url'; // again, pass in somewhere or get from DOM
var sortType = 'asc';
function filter(data, filter) {
var filteredResults = data.filter(function (el) {
return (filter !== '' && el.url.toLowerCase().indexOf(filter.toLowerCase())) !== -1;
})
return filteredResults;
}
function sort(data, sortBy, sortType) {
var sortIndex = sortType === "asc" ? 1 : -1;
data.sort(function (a, b) {
if (a[sortBy] < b[sortBy]) {
return -1 * sortIndex;
} else if (a[sortBy] > b[sortBy]) {
return 1 * sortIndex;
}
return 0;
})
}
var filteredResults = filter(dataset, filterValue);
sort(dataset, sortBy, sortType); //dataset will be sorted
I am facing a strange issue while writing a Breeze.js with Durandal SPA (largely based on John Papa's Great SPA Jumpstart (https://github.com/johnpapa/PluralsightSpaJumpStartFinal) training ), the issue when a try to make the same server API call multiple times consecutively the server is hit only once and one the second call it seems I get cached data (call doesn't even hit server), this can be replicated in Jumpstart sample too, below is the modified code to replicate this on Jumpstart
var activate = function () {
for (var i = 0 ; i < 2 ; i++) {
datacontext.getSessionPartials(sessions, true);
}
};
var activate = function () {
for (var i = 0 ; i < 2 ; i++)
{
datacontext.getSpeakerPartials(speakers, true);
}
};
Edit- Updated with the complete code :
Code of my Viewmodel
define(['services/datacontext'], function (datacontext) {
var speakers = ko.observableArray();
var activate = function () {
for (var i = 0 ; i < 2 ; i++)
{
datacontext.getSpeakerPartials(speakers, true);
}
};
var refresh = function () {
return datacontext.getSpeakerPartials(speakers, true);
};
var vm = {
activate: activate,
speakers: speakers,
title: 'Speakers',
refresh: refresh
};
return vm;
});
Below is code of my datacontext/service :
define([
'durandal/system',
'services/model',
'config',
'services/logger',
'services/breeze.partial-entities'],
function (system, model, config, logger, partialMapper) {
var EntityQuery = breeze.EntityQuery;
var manager = configureBreezeManager();
var orderBy = model.orderBy;
var entityNames = model.entityNames;
var getSpeakerPartials = function (speakersObservable, forceRemote) {
if (!forceRemote) {
var p = getLocal('Persons', orderBy.speaker);
if (p.length > 0) {
speakersObservable(p);
return Q.resolve();
}
}
var query = EntityQuery.from('Speakers')
.select('id, firstName, lastName, imageSource')
.orderBy(orderBy.speaker);
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
var list = partialMapper.mapDtosToEntities(
manager, data.results, entityNames.speaker, 'id');
if (speakersObservable) {
speakersObservable(list);
}
log('Retrieved [Speaker] from remote data source',
data, true);
}
};
var getSessionPartials = function (sessionsObservable, forceRemote) {
if (!forceRemote) {
var s = getLocal('Sessions', orderBy.session);
if (s.length > 3) {
// Edge case
// We need this check because we may have 1 entity already.
// If we start on a specific person, this may happen. So we check for > 2, really
sessionsObservable(s);
return Q.resolve();
}
}
var query = EntityQuery.from('Sessions')
.select('id, title, code, speakerId, trackId, timeSlotId, roomId, level, tags')
.orderBy('timeSlotId, level, speaker.firstName');
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
var list = partialMapper.mapDtosToEntities(
manager, data.results, entityNames.session, 'id');
if (sessionsObservable) {
sessionsObservable(list);
}
log('Retrieved [Sessions] from remote data source',
data, true);
}
};
var getSessionById = function(sessionId, sessionObservable) {
// 1st - fetchEntityByKey will look in local cache
// first (because 3rd parm is true)
// if not there then it will go remote
return manager.fetchEntityByKey(
entityNames.session, sessionId, true)
.then(fetchSucceeded)
.fail(queryFailed);
// 2nd - Refresh the entity from remote store (if needed)
function fetchSucceeded(data) {
var s = data.entity;
return s.isPartial() ? refreshSession(s) : sessionObservable(s);
}
function refreshSession(session) {
return EntityQuery.fromEntities(session)
.using(manager).execute()
.then(querySucceeded)
.fail(queryFailed);
}
function querySucceeded(data) {
var s = data.results[0];
s.isPartial(false);
log('Retrieved [Session] from remote data source', s, true);
return sessionObservable(s);
}
};
var cancelChanges = function() {
manager.rejectChanges();
log('Canceled changes', null, true);
};
var saveChanges = function() {
return manager.saveChanges()
.then(saveSucceeded)
.fail(saveFailed);
function saveSucceeded(saveResult) {
log('Saved data successfully', saveResult, true);
}
function saveFailed(error) {
var msg = 'Save failed: ' + getErrorMessages(error);
logError(msg, error);
error.message = msg;
throw error;
}
};
var primeData = function () {
var promise = Q.all([
getLookups(),
getSpeakerPartials(null, true)])
.then(applyValidators);
return promise.then(success);
function success() {
datacontext.lookups = {
rooms: getLocal('Rooms', 'name', true),
tracks: getLocal('Tracks', 'name', true),
timeslots: getLocal('TimeSlots', 'start', true),
speakers: getLocal('Persons', orderBy.speaker, true)
};
log('Primed data', datacontext.lookups);
}
function applyValidators() {
model.applySessionValidators(manager.metadataStore);
}
};
var createSession = function() {
return manager.createEntity(entityNames.session);
};
var hasChanges = ko.observable(false);
manager.hasChangesChanged.subscribe(function(eventArgs) {
hasChanges(eventArgs.hasChanges);
});
var datacontext = {
createSession: createSession,
getSessionPartials: getSessionPartials,
getSpeakerPartials: getSpeakerPartials,
hasChanges: hasChanges,
getSessionById: getSessionById,
primeData: primeData,
cancelChanges: cancelChanges,
saveChanges: saveChanges
};
return datacontext;
//#region Internal methods
function getLocal(resource, ordering, includeNullos) {
var query = EntityQuery.from(resource)
.orderBy(ordering);
if (!includeNullos) {
query = query.where('id', '!=', 0);
}
return manager.executeQueryLocally(query);
}
function getErrorMessages(error) {
var msg = error.message;
if (msg.match(/validation error/i)) {
return getValidationMessages(error);
}
return msg;
}
function getValidationMessages(error) {
try {
//foreach entity with a validation error
return error.entitiesWithErrors.map(function(entity) {
// get each validation error
return entity.entityAspect.getValidationErrors().map(function(valError) {
// return the error message from the validation
return valError.errorMessage;
}).join('; <br/>');
}).join('; <br/>');
}
catch (e) { }
return 'validation error';
}
function queryFailed(error) {
var msg = 'Error retreiving data. ' + error.message;
logError(msg, error);
throw error;
}
function configureBreezeManager() {
breeze.NamingConvention.camelCase.setAsDefault();
var mgr = new breeze.EntityManager(config.remoteServiceName);
model.configureMetadataStore(mgr.metadataStore);
return mgr;
}
function getLookups() {
return EntityQuery.from('Lookups')
.using(manager).execute()
.then(processLookups)
.fail(queryFailed);
}
function processLookups() {
model.createNullos(manager);
}
function log(msg, data, showToast) {
logger.log(msg, data, system.getModuleId(datacontext), showToast);
}
function logError(msg, error) {
logger.logError(msg, error, system.getModuleId(datacontext), true);
}
//#endregion
});
Below is the code for BreezeController/WebApi
namespace CodeCamper.Controllers
{
[BreezeController]
public class BreezeController : ApiController
{
readonly EFContextProvider<CodeCamperDbContext> _contextProvider =
new EFContextProvider<CodeCamperDbContext>();
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
[HttpGet]
public object Lookups()
{
var rooms = _contextProvider.Context.Rooms;
var tracks = _contextProvider.Context.Tracks;
var timeslots = _contextProvider.Context.TimeSlots;
return new {rooms, tracks, timeslots};
}
[HttpGet]
public IQueryable<Session> Sessions()
{
return _contextProvider.Context.Sessions;
}
[HttpGet]
public IQueryable<Person> Persons()
{
return _contextProvider.Context.Persons;
}
[HttpGet]
public IQueryable<Person> Speakers()
{
return _contextProvider.Context.Persons
.Where(p => p.SpeakerSessions.Any());
}
}
}
Please help/advise.
Apologies if I'm haven't found it in the documentation yet...
Q: How do you change the queryformat for an ajax call in Railo?
Here's my component:
component {
remote function Read() returnformat='json' {
svc = new Query();
svc.setSQL("SELECT * FROM INFORMATION_SCHEMA.TABLES");
obj = svc.execute();
local.result.Prefix = obj.getPrefix();
local.result.qry = obj.getResult();
url.queryFormat = "column";
return local.result;
}
}
and here's my JavaScript:
(function() {
var local = {};
local.type = 'POST';
local.url = 'AJAX.cfc';
local.dataType = 'json';
local.data = {};
local.data.method = 'Read';
local.Promise = $.ajax(local);
local.Promise.done(done);
local.Promise.fail(fail);
function done(response) {
console.log(response);
debugger;
}
function fail(xhr,status,response) {
debugger;
}
})();
What I'm getting back is:
response.qry.DATA[] // 57 arrays, each of length 4
But ColdFusion returns this, which I've grown fond of using (being able to use the column names instead of the array position):
response.qry.DATA.TABLE_CATALOG[] // An array of 57 elements
response.qry.DATA.TABLE_SCHEMA[]
response.qry.DATA.TABLE_NAME[]
response.qry.DATA.TABLE_TYPE[]
Use ReturnFormat="plain" on the function, and pass true for the 2nd argument of serializeJson()
serializeJson(Query, true)
That will give you a JSON object that is serialized by Column, so you can just return it.