How to print in drop-down list in jxs? - reactjs

How to print in drop-down list in jxs? Actually I'm having drop-down list and by this code i'm getting all the data in one single row while clicking on it but I want it in list. Can anyone help me out for this?
My code:
comboClick () {
var apiBaseUrl = "http://api.eventsacross-stage.railsfactory.com/api/";
var input = this.state.search_event;
let self = this;
let location = [];
let cityArray = [];
axios.get(apiBaseUrl+'v1/events/?on_dashboard=false'+input)
.then(function (response) {
let events = response.data.events;
for(var i = 0; i < response.data.events_count; i++) {
var obj = response.data.events[i];
location.push(obj.locations[0].city);
}
let cityUnique = _.uniq(location, 'city');
cityArray.push(cityUnique);
self.setState({cityArray: cityArray});
})
.catch(function (error) {
console.log(error);
});console.log("cityArray",cityArray);
}
jsx part:
render() {
var cityFilter = [this.state.cityArray ? this.state.cityArray[0] : null];
{console.log("cityFilter",cityFilter)}
return (...
<div className="dropdown text-center">
<button
className="btn btn-default dropdown-toggle"
type="button"
data-toggle="dropdown"
style={{width: "50%"}}
onClick={this.comboClick.bind(this)}>
Place
<span className="caret"></span>
</button>
<ul className="dropdown-menu">
{cityFilter.map(function(city, index){
return <li className="text-center" key={ index }>{city}</li>;
})}
</ul>
</div>
...}

Related

Angular Image Array edit with api binding

I'm stuck in the image array where I can patch image array value in my edit form there can I upload other images or push images that array or delete.
I have a product model where I can have a sub-array where I can trigger edit query or patch value.
onSelectFile(event: any) {
if (event.target.files && event.target.files[0]) {
var filesAmount = event.target.files.length;
for (let i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = (event: any) => {
console.log("image1",event.target.result);
this.urls.push(event.target.result);
};
reader.readAsDataURL(event.target.files[i]);
}
}
}
<div class="fileupload-wrapper">
<div>
<button class="file-upload-button" type="button" for="custom-fileupload">
<img src="assets/images/icons/file-upload.svg"
alt="file-upload"><span>Upload</span>
<input type="file" accept="image/*;base64," id="file" #file
(change)="onSelectFile($event)" id="custom-fileupload" class="custom-fileupload" multiple />
</button>
</div>
<span class="file-info">
<div *ngFor='let url of urls; let i = index' class="category-wrapper">
<img [src]="sanitizeImageUrl(url)" *ngIf="url" class="categroy-images">
<span (click)="resetCoverValue(i)" class="cross-icon">{{ this.documentName ?
"close" : null }}
<img src="assets/images/icons/blue-cross.svg">
</span>
</div>
</span>
</div>

Apply filter using ng-repeat results

I have a problem filtering results depending on ID of previous get request:
$http.get('https://www.immobiliaremartina.it/inc/show_all.php')
.success(function (data) {$scope.results = data;})
.error(function () {alert("Errore di connessione!")})
$http.get('https://www.immobiliaremartina.it/inc/showFoto.php')
.success(function (data) {$scope.fotos = data;})
.error(function () {alert("Errore di connessione!")})
After this two calls I want to show all pics in fotos depending on the ID of results
<div class="slider gal" >
<ul class="slides" >
<li ng-repeat="foto in fotos | filter: result.ID === foto.ID">
<img src="/public/galleria/{{foto.URL}}">
</li>
</ul>
</div>
how is this possible?
You can try the following
js
$scope.data = [];
var fotos = $http.get('https://www.immobiliaremartina.it/inc/showFoto.php')
var results = $http.get('https://www.immobiliaremartina.it/inc/show_all.php')
$q.all([fotos, results]).then(data => {
var fotoResult = data[0];
var resultResult = data[1];
for(i= 0; i< fotoResult.length;i++){
for(j = 0; j < resultResult.length;j++){
if(fotoResult[i].ID === resultResult[j].ID){
$scope.data.push(fotoResult[i]);
}
}
}
});
html
<div class="slider gal" >
<ul class="slides" >
<li ng-repeat="foto in data>
<img src="/public/galleria/{{foto.URL}}">
</li>
</ul>
</div>
the above code waits for the results of both of your http requests and when they are loaded it filters data in your controller and shows filtered data in your html.
Create a function:
$scope.isInResults = function(foto){
return results.filter((result) => result.id === foto.id)
};
and then
<li ng-repeat="foto in fotos | filter: isInResults">
<img src="/public/galleria/{{foto.URL}}">
</li>

Service Portal Widget form Returns "Record not Found"

I created new widget by cloning existing form widget in Service Portal (ServiceNow). Modified sys_id and table name in the URL (https://dev32223.service-now.com/aaportal/?id=departments&table=x_34334_aaaa_incident&sys_id=ee384830db2e32001cf8dec0cf9619de). Created new page with the widget and the resulting web page shows 'Record Not Found'
HTML:
<div ng-if="!data.isValid && !data.emptyStateTemplate" class="panel panel-default">
<div class="panel-body wrapper-lg text-center">
${Record not found}
</div>
</div>
<div ng-if="!data.isValid && data.emptyStateTemplate" class="panel-shift">
<div class="empty-state-wrapper panel panel-default" ng-include="data.emptyStateTemplate"></div>
</div>
<div ng-if="data.isValid" class="panel-shift">
<div class="" ng-if="!data.f._view.length && data.hideRelatedLists && data.emptyStateTemplate">
<div class="empty-state-wrapper panel panel-default" ng-include="data.emptyStateTemplate"></div>
</div>
<div class="" ng-if="!data.f._view.length && data.hideRelatedLists && !data.emptyStateTemplate">
<div class="panel panel-default">
<div class="panel-heading"><span class="panel-title">{{data.f.title}}</span> <span ng-if="options.showFormView == 'true' && data.f.view != ''">[{{data.f.view_title}} view]</span></div>
<div class="panel-body wrapper-lg text-center">
${No elements to display}
</div>
</div>
</div>
<div class="panel panel-default" ng-if="data.f._view.length || !data.hideRelatedLists" >
<div class="panel-heading" ng-if="data.f.title.length" sp-context-menu="getUIActionContextMenu(event)">
<span class="dropdown m-r-xs" ng-if="(data.isAdmin || getUIActions('context').length > 0) && options.omitHeaderOptions != 'true'">
<span class="dropdown-toggle glyphicon glyphicon-menu-hamburger" style="line-height: 1.4em" id="adminMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"></span>
<ul class="dropdown-menu" aria-labelledby="adminMenu">
<li ng-if="::data.isAdmin">${Open in platform}</li>
<li ng-if="::data.isAdmin" class="dropdown-header">${Configure}</li>
<li ng-if="::data.isAdmin">${Form Layout}</li>
<li ng-if="::data.isAdmin">${Related Lists}</li>
<li ng-if="::data.isAdmin">${UI Policies} <span class="badge pull-right" ng-if="f.policy.length">{{f.policy.length}}</span></li>
<li ng-if="::data.isAdmin">${Client Scripts} <span class="badge pull-right" ng-if="adminMenu.getClientScriptCount()">{{adminMenu.getClientScriptCount()}}</span></li>
<li ng-if="getUIActions('context').length > 0 && data.isAdmin" role="separator" class="divider"></li>
<li ng-repeat="action in getUIActions('context')">{{action.name}}</li>
<li ng-if="::data.isAdmin || getUIActions('context').length > 0" role="separator" class="divider"></li>
<li><a target="_new" href="/{{data.f.table}}.do?PDF&sys_id={{data.sys_id}}&sysparm_view={{data.f.view}}">${Export to PDF}</a></li>
<li><a target="_new" href="/{{data.f.table}}.do?PDF&landscape=true&sys_id={{data.sys_id}}&sysparm_view={{data.f.view}}">${Export to PDF (landscape)}</a></li>
</ul>
</span>
<span class="panel-title">{{data.f.title}}</span> <span ng-if="options.showFormView == 'true' && data.f.view != ''">[{{data.f.view_title}} view]</span>
<div ng-if="attachmentHandler && data.canAttach" title="{{::data.addAttachmentMsg}}" class="pull-right attachment-button">
<sp-attachment-button></sp-attachment-button>
</div>
</div>
<div class="panel-body">
<!-- performance debug -->
<div ng-if="data.show_sql">
<div class="comment">
<span ng-if="data.f._perf.sql_count">${SQL Statements {{data.f._perf.sql_count}}}, </span>
<span>${Time {{data.f._perf.time}}}</span>
</div>
<div ng-repeat="s in data.f._perf.sql" class="{{s.type}}">
{{s.statement}}
</div>
</div>
<!-- attachments -->
<sp-attachment-manager table="data.table" sys-id="data.f._attachmentGUID" omit-edit="!data.canAttach"></sp-attachment-manager>
<!-- form -->
<div>
<sp-model form_model="data.f" mandatory="mandatory"></sp-model>
</div>
<!-- UI Action Links -->
<div ng-if="getUIActions('link').length > 0">
<label style="margin: 0;">${Related Links}</label>
<div ng-repeat="action in getUIActions('link')">
<a href ng-click="triggerUIAction(action)">{{action.name}}</a>
</div>
</div>
<!-- related lists -->
<div ng-if="!data.hideRelatedLists">
<label style="margin: 0">${Related Lists}</label>
<div style="margin-bottom: 7px; padding-bottom: 7px; border-bottom: 1px solid #f5f5f5;">
<span ng-repeat="rl in data.f._related_lists" ng-if="rl.visible">
<a ng-if="rl.type != 'REL'" href="?id=lf&table={{rl.table}}&filter={{rl.field}}%3D{{data.f.sys_id}}&view={{data.f.view}}" ng-click="openRelatedList($event, {id: 'lf', table: '{{rl.table}}', filter: '{{rl.field}}%3D{{data.f.sys_id}}'})">{{rl.plural}}
<span class="label label-as-badge label-primary" ng-if="rl.count">{{rl.count}}</span>
</a>
<a ng-if="rl.type == 'REL'" href="?id=lf&table={{rl.table}}&relationship_id={{rl.relationship_id}}&apply_to={{rl.apply_to}}&apply_to_sys_id={{rl.apply_to_sys_id}}&view={{data.f.view}}" ng-click="openRelatedList($event, {id: 'lf', table: '{{rl.table}}', apply_to: '{{rl.apply_to}}', apply_to_sys_id: '{{rl.apply_to_sys_id}}', relationship_id: '{{rl.relationship_id}}'})">{{rl.label}}
<span class="label label-as-badge label-primary" ng-if="rl.count">{{rl.count}}</span>
</a>
<span ng-if="!$last" style="padding-left: .5em; padding-right: .5em;"> | </span>
</span>
</div>
</div>
</div>
<div class="panel-footer">
<button ng-mousedown="triggerUIAction(action)" ng-repeat="action in getUIActions('button')" class="btn btn-default action-btn">{{action.name}}</button>
<span>{{status}}</span>
<button ng-if="getPrimaryAction()" type="submit" ng-mousedown="triggerUIAction(getPrimaryAction())" class="btn btn-primary action-btn pull-right">${Save} <span ng-if="saveButtonSuffix">(${{{saveButtonSuffix}}})</span></button>
<div style="clear: both;"></div>
<div ng-if="mandatory.length" class="alert alert-info" style="margin-top: .5em">
<span ng-if="mandatory.length > 0">${Required information} </span>
<span ng-repeat="f in mandatory" class="label label-danger" style="margin-right: .5em; display: inline-block;">{{f.label}}</span>
</div>
</div>
</div>
</div>
Client Script:
function ($scope, $rootScope, $timeout, spUtil, $location, $window, nowAttachmentHandler) {
$scope.mandatory = [];
$scope.data.show_sql = false;
$scope.saveButtonSuffix = spUtil.getAccelerator('s');
$scope.adminMenu = {
encodedPageUrl: encodeURIComponent($location.url()),
getClientScriptCount: function() {
var count = 0;
if ($scope.data.f.client_script) {
count += $scope.data.f.client_script.onChange.length;
count += $scope.data.f.client_script.onLoad.length;
count += $scope.data.f.client_script.onSubmit.length;
}
return count;
}
};
$scope.getUIActions = function(type) {
if ($scope.data.disableUIActions)
return [];
if (type) {
return $scope.data.f._ui_actions.filter(function(action) {
//We handle the primary action button separately.
return !action.primary && action['is_' + type];
});
} else {
return $scope.data.f._ui_actions;
}
}
$scope.getPrimaryAction = function() {
var primaryActions = $scope.data.f._ui_actions.filter(function(action) {
return action.primary;
});
return (primaryActions.length) ? primaryActions[0] : null;
}
$scope.getUIActionContextMenu = function(event) {
var menu = [];
if (event.ctrlKey)
return menu;
var contextActions = $scope.getUIActions('context');
contextActions.forEach(function(action) {
menu.push([action.name, function() {
$scope.triggerUIAction(action);
}]);
});
if (contextActions.length > 0)
menu.push(null);
menu.push([$scope.data.exportPDFMsg, function() {exportPDF("");}]);
menu.push([$scope.data.exportPDFLandMsg, function() {exportPDF('true');}]);
return menu;
}
function exportPDF(landscape) {
$window.open("/" + $scope.data.f.table + ".do?PDF&landscape=" + landscape + "&sys_id=" + $scope.data.sys_id + "&sysparm_view=" + $scope.data.f.view);
}
//trigger the primary UI Action on save (if there is one)
var deregister = $scope.$on('$sp.save', function() {
var primaryAction = $scope.getPrimaryAction();
if (primaryAction)
$scope.triggerUIAction(primaryAction);
});
$scope.$on('$destroy', function() {deregister()});
$scope.triggerUIAction = function(action) {
if ($scope.data.disableUIActions)
return;
if (g_form) {
$timeout(function() {
g_form.submit(action.action_name || action.sys_id);
});
}
}
$scope.$on("spModel.uiActionComplete", function(evt, response) {
var sysID = (response.isInsert) ? response.sys_id : $scope.data.sys_id;
loadForm($scope.data.table, sysID).then(constructResponseHandler(response));
});
function constructResponseHandler(response) {
return function() {
var message;
var eventName = "sp.form.record.updated";
if (response.isInsert) {
message = $scope.data.recordAddedMsg;
var search = $location.search();
search.sys_id = response.sys_id;
search.spa = 1;
$location.search(search).replace();
} else
message = $scope.data.updatedMsg;
$scope.data.hideRelatedLists = hideRelatedLists();
$scope.$emit(eventName, $scope.data.f._fields);
$rootScope.$broadcast(eventName, $scope.data.f._fields);
$scope.status = message;
spUtil.addTrivialMessage(message);
$timeout(clearStatus, 2000);
}
}
var ctrl = this;
// switch forms
var unregister = $scope.$on('$sp.list.click', onListClick);
$scope.$on("$destroy", function() {
unregister();
})
function onListClick(evt,arg) {
loadForm(arg.table, arg.sys_id);
}
function loadForm(table, sys_id){
var f = {};
//$scope.data.table = f.table = 'x_19668_halo_incident';
//$scope.data.sys_id = f.sys_id ='ee384830db2e32001cf8dec0cf9619de';
$scope.data.table = f.table = table;
$scope.data.sys_id = f.sys_id = sys_id;
f.view = $scope.data.view;
return $scope.server.update().then(setupAttachmentHandler);
}
function openRelatedList(e, queryString){
// todo: Open this in a modal
$location.search(queryString);
e.preventDefault();
}
$scope.$on('spModel.fields.rendered', function() {
if (ctrl.panels)
ctrl.panels.removeClass('shift-out').addClass('shift-in');
});
var g_form;
$scope.$on('spModel.gForm.initialized', function(e, gFormInstance) {
if (gFormInstance.getTableName() == $scope.data.f.table)
g_form = gFormInstance;
});
// Show or hide related lists
$scope.$watch('data.f._related_lists', function(){
$scope.data.hideRelatedLists = hideRelatedLists();
}, true);
function hideRelatedLists() {
if (!$scope.data.f._related_lists)
return true;
if ($scope.options.hideRelatedLists == true)
return true;
if ($scope.data.sys_id == '-1')
return true;
// If all related lists are visible=false then hide
if ($scope.data.f._related_lists.length > 0) {
for (var i in $scope.data.f._related_lists) {
var list = $scope.data.f._related_lists[i];
if (list.visible) {
return false;
}
}
}
return true;
}
function clearStatus() {
$scope.status = "";
}
function setupAttachmentHandler(){
$scope.attachmentHandler = new nowAttachmentHandler(appendSuccess, appendError);
$timeout(function() {
var sizeLimit = 1024 * 1024 * 24; // 24MB
$scope.attachmentHandler.setParams($scope.data.table, $scope.data.f._attachmentGUID, sizeLimit);
});
$scope.$on('dialog.upload_too_large.show', function(e){
console.log($scope.data.largeAttachmentMsg);
spUtil.addErrorMessage($scope.data.largeAttachmentMsg);
});
}
setupAttachmentHandler();
function appendSuccess() {
spUtil.addTrivialMessage($scope.data.attachmentUploadSuccessMsg);
$scope.$broadcast("sp.attachments.update", $scope.data.f._attachmentGUID);
}
function appendError(error) {
$scope.errorMessages.push(error);
}
}
Server Script:
// form functionality - URL parameter driven
(function($sp, input, data, options, gs)
{
/* "use strict"; -linter issues */
// populate the 'data' variable
data.attachmentUploadSuccessMsg = gs.getMessage("Attachment upload was successful");
data.recordAddedMsg = gs.getMessage("Record Added");
data.updatedMsg = gs.getMessage("updated_uppercase");
data.exportPDFMsg = gs.getMessage("Export to PDF");
data.exportPDFLandMsg = gs.getMessage("Export to PDF (landscape)");
data.addAttachmentMsg = gs.getMessage("Add an attachment");
data.largeAttachmentMsg = gs.getMessage("Attached files must be smaller than {0} - please try again", "24MB");
data.isAdmin = true;
data.emptyStateTemplate = options.empty_state_template;
data.disableUIActions = options.disableUIActions || false;
data.hideRelatedLists = options.hideRelatedLists || false;
if (input) {
data.table = input.table;
data.sys_id = input.sys_id;
data.view = input.view;
var result = {};
if (input._fields)
result = $sp.saveRecord(input.table, input.sys_id, input._fields);
if (input.sys_id == '-1'){
data.sys_id = result.sys_id;
data.isNewRecord = true;
}
} else {
data.table = $sp.getParameter("t") || $sp.getParameter("table") || $sp.getParameter("sl_table") || options.table;
data.sys_id = $sp.getParameter("sys_id") || $sp.getParameter("sl_sys_id") || options.sys_id;
data.view = $sp.getParameter("v") || $sp.getParameter("view") || options.view; // no default
}
data.query = $sp.getParameter("query") || options.query;
data.f = {};
if (!data.table)
return;
//if (!GlideTableDescriptor.isValid(data.table))
//return;
if (!data.sys_id)
return;
gs.info("data.table, data.sys_id 3:");
var rec = $sp.getRecord(data.table, data.sys_id); gs.info("data.table, data.sys_id 31:");
data.isValid = rec.isValid() || data.sys_id == "-1"; gs.info("data.table, data.sys_id 32:");
gs.info("data.table, data.sys_id 4:");
if (!data.isValid)
return;
gs.info("data.table, data.sys_id :"+data.table+ data.sys_id);
data.table = rec.getRecordClassName();
data.tableHierarchy = GlideDBObjectManager.getTables(data.table).toArray().join();
data.canWrite = rec.canWrite();
data.canAttach = data.canWrite && gs.hasRole(gs.getProperty('glide.attachment.role')) && !GlideTableDescriptor.get(data.table).getED().getBooleanAttribute("no_attachment");
data.f = $sp.getForm(data.table, data.sys_id, data.query, data.view);
// Activity formatter is hardcoded to set specific options
for (var f in data.f._formatters) {
var fm = data.f._formatters[f];
if (fm.formatter == "activity.xml") {
fm.hardcoded = true;
fm.widgetInstance = $sp.getWidget('widget-ticket-conversation',
{table: data.table,
sys_id: data.sys_id,
includeExtended: true,
title: "${Activity}",
placeholder: "${Add a comment}",
btnLabel: "${Post}"});
} else
fm.widgetInstance = $sp.getWidget(fm.widget, data);
}
})($sp, input, data, options, gs);
It looks like the control is not passing the line var rec = $sp.getRecord(data.table, data.sys_id); I can not figure out the issue, but I have an alternate solution. You can use iframes (shown below) to show form or list of records.
Mark it as answer if this answers your question.

Filtering from to letter in Angular

I have been through a few of those questions on Stackoverflow and found this link from a thread:http://toddmotto.com/everything-about-custom-filters-in-angular-js/ which is great but I am struggling to adapt it to what I need to do.
I am trying to implement a simple function based on it which will have a button group one which shows all results then from and to letter such as:
<button type="button" class="btn btn-primary">All</button>
<button type="button" class="btn btn-primary”>A-E</button>
<button type="button" class="btn btn-primary">F-K</button>
<button type="button" class="btn btn-primary">L-P</button>
However I am unable to adapt the function to perform this filter. I can only do with the basic filter by single letter.
<button type="button" class="btn btn-primary" ng-click="letter = 'C'">C</button>
I am also unable to show “all results"
Here is my app code:
var app = angular.module (‘app', []);
app.controller('PersonCtrl', function () {
this.friends = [{
name: 'Andrew'
},
{
name: 'Bob'
},{
name: 'Beano'
},{
name: 'Chris'
}, {
name: 'Will'
}, {
name: 'Mark'
}, {
name: 'Alice'
}, {
name: 'Todd'
}];
});
app.filter('startsWithLetter', function () {
return function (items, letter) {
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.name.substring(0, 1))) {
filtered.push(item);
}
}
return filtered;
};
});
HTML CONTROLLER CODE:
<div class="container" ng-controller="PersonCtrl as person">
<ul>
<li ng-repeat="friend in person.friends | startsWithLetter:letter">
{{ friend }}
</li>
</ul>
</div>
How do I adapt this to perform more specific filtering?
You can use colons to pass multiple arguments to your filter - fromLetter and toLetter as well as your input.
<li ng-repeat="friend in person.friends | startsWithLetter:person.fromLetter:person.toLetter">
{{ friend }}
</li>
Then you can lowercase the first letter of the string and compare this directly to fromLetter and toLetter
app.filter('startsWithLetter', function () {
return function (items, fromLetter, toLetter) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
var firstLetter = item.name.substring(0, 1).toLowerCase();
if ((!fromLetter || firstLetter >= fromLetter)
&& (!toLetter || firstLetter <= toLetter)) {
filtered.push(item);
}
}
return filtered;
};
});
That means that the button logic needs to be slightly more complex and set two variables:
<button type="button" class="btn btn-primary" ng-click="person.setLetters()">All</button>
<button type="button" class="btn btn-primary" ng-click="person.setLetters('a','e')">A-E</button>
<button type="button" class="btn btn-primary" ng-click="person.setLetters('f','k')">F-K</button>
<button type="button" class="btn btn-primary" ng-click="person.setLetters('l','p')">L-P</button>
and on your controller:
this.setLetters = function(from, to){
this.fromLetter = from;
this.toLetter = to;
};
JSFiddle
You could have filtering based on the alphabet ASCII codes. On button click set the range of ASCII code using ng-click directive with - separated value like letter='65-69. Then that range will pass through the the filter, out of which first parameter is upperLimit & 2nd one is lowerLimit of the selected range. For comparing the starting variable ASCII value we could use string.charCodeAt('0') method which will return ASCII value of first character & will compare that value with the range variable inside foreach loop.
Markup
<div class="container" ng-controller="PersonCtrl as person">
<ul>
<li ng-repeat="friend in person.friends | startsWithLetter:letter">
{{ friend }}
</li>
</ul>
<button type="button" class="btn btn-primary" ng-click="letter=''">All</button>
<button type="button" class="btn btn-primary" ng-click="letter='65-69'">A-E</button>
<button type=" button " class="btn btn-primary" ng-click="letter='70-75'">F-K</button>
<button type="button " class="btn btn-primary " ng-click="letter='76-80'">L-P</button>
</div>
Filter
app.filter('startsWithLetter', function() {
return function(items, letter) {
if (!letter || letter.length == 0)
return items;
var filtered = [],
range = letter.split('-');
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
for (var j = parseInt(range[0]); j <= parseInt(range[1]); j++) {
if (item.name.charCodeAt('0') == j) {
filtered.push(item);
}
}
}
return filtered;
};
});
Working PLunkr

ng-repeat store separate values

I want to store the users vote's inside a cookie, the problem is that inside the ng-repeat I have a value called session.upVoteCount. But it is supposed to be a separate value for each event list item. Is it possible to store each upVoteCount separately and then retrieve them separately again?
<li ng-repeat="session in event.sessions | filter:query | orderBy:sortorder" class="span11">
<div class="row session">
<div class="col-sm-1 well votingWidget">
<div class="votingButton" ng-click="upVoteSession(session)">
<span class="glyphicon glyphicon-arrow-up"></span>
</div>
<div class="badge badge-inverse">
<div>{{session.upVoteCount}}</div>
</div>
<div class="votingButton" ng-click="downVoteSession(session)">
<span class="glyphicon glyphicon-arrow-down"></span>
</div>
</div>
</div>
</li>
and in my controller I have this:
$scope.upVoteSession = function(session) {
session.upVoteCount++;
};
$scope.downVoteSession = function(session) {
session.upVoteCount--;
};
First, I don't recommend to use term 'session', but 'votes'. However, it's your call.
I simplify your problem in this example
http://plnkr.co/edit/l7tQRbuOtEDJetY5eTsf?p=preview
Javascript:
function MyCtrl($scope) {
$scope.votes = {};
$scope.vote = function(key, val) {
$scope.votes[key] = $scope.votes[key] || 0;
$scope.votes[key]+= val;
};
}
Html:
<li ng-repeat="no in [1,2,3,4,5]">
{{no}} : {{votes[no]}} <br/>
upvote
downvote
</li>
Hi guys I solved it myself, I could not get it to work with JSfiddle so I have uploaded the entire thing. Click on server.bat and browser to localhost:8000/eventdetails.html and you will see it working.
https://mega.co.nz/#!1d9yiYiA!zTzdztLAmhVDVYOvvVLINETI2bo_WjxCBteWYm2VUKc
controller:
eventsApp.controller('EventController',
function EventController($scope, $cookieStore, eventData) {
$scope.sortorder = 'name';
var ape = eventData.getEvent();
ape.then(function (banana) {
$scope.event = banana;
angular.forEach(banana.sessions, function (value, key) {
var storecookie = ($cookieStore.get(value.name));
if (typeof storecookie !== "undefined") {
value.upVoteCount = storecookie;
}
});
});
$scope.upVoteSession = function (session) {
session.upVoteCount++;
$cookieStore.put(session.name, session.upVoteCount);
};
$scope.downVoteSession = function (session) {
session.upVoteCount--;
$cookieStore.put(session.name, session.upVoteCount);
};
}
);

Resources