Manually trigger slickgrid events - javascript

I want to manually trigger slickgrid event. For eg: I want to change current cell to move down when i press down arrow. This i can achieve only when slickgrid is in focus, once the focus is lost to the web page, pressing down arrow will not change active cell.
I tried this:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>SlickGrid example 1: Basic grid</title>
<link rel="stylesheet" href="mycss/slick.grid.css" type="text/css"/>
<link rel="stylesheet" href="mycss/smoothness/jquery-ui-1.8.16.custom.css" type="text/css"/>
<link rel="stylesheet" href="mycss/examples.css" type="text/css"/>
</head>
<body>
<div>
<p id="p_title"></p>
<p id="p_duration"></p>
<p id="p_Complete"></p>
<p id="p_start"></p>
<p id="p_finish"></p>
<p id="p_effort-driven"></p>
</div>
<table width="100%">
<tr>
<td valign="top" width="50%">
<div id="myGrid" style="width:600px;height:500px;"></div>
</td>
</tr>
</table>
<script src="js/lib/jquery-1.7.min.js"></script>
<script src="js/lib/jquery.event.drag-2.2.js"></script>
<script src="js/slick.core.js"></script>
<script src="js/slick.grid.js"></script>
<script src="js/slick.dataview.js"></script>
<script>
var grid;
var dataView;
var curr_row;
var columns = [
{id: "title", name: "Title", field: "title"},
{id: "duration", name: "Duration", field: "duration"},
{id: "%", name: "% Complete", field: "percentComplete"},
{id: "start", name: "Start", field: "start"},
{id: "finish", name: "Finish", field: "finish"},
{id: "effort-driven", name: "Effort Driven", field: "effortDriven"}
];
var options = {
enableCellNavigation: true,
enableColumnReorder: false
};
$(function () {
var data = [];
for (var i = 0; i < 50; i++) {
data[i] = {
id: i,
title: "Task " + i,
duration: "5 days",
percentComplete: Math.round(Math.random() * 100),
start: "01/01/2009",
finish: "01/05/2009",
effortDriven: (i % 5 == 0)
};
}
dataView = new Slick.Data.DataView();
dataView.setItems(data);
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.onKeyDown.subscribe(function (e, args) {
if (e.which == 38) {
curr_row= args.row - 1;
sata(curr_row)
}
if (e.which == 40){
curr_row = args.row + 1;
sata(curr_row)
}
});
grid.onClick.subscribe(function (e, args){
curr_row = args.row;
sata(curr_row)
});
});
function sata(row){
var row_data = dataView.getItem(row); // Read from dataView not the grid data
var cell_contents = row_data['title'];
alert(cell_contents);
}
$(document).keydown(function(e) {
if (e.which == 38) {
curr_row= curr_row - 1;
grid.onClick.notify({row:curr_row})
}
if (e.which == 40){
curr_row = curr_row + 1;
grid.onClick.notify({row:curr_row})
}
});
</script>
</body>
</html>
But, even though i can now get active cell data, the grid not updated (render not refreshed)
Any advice on how to make slickgrid to react to such global events will be highly appreciated. Thanks in advance.

This code addresses my issue,
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>SlickGrid example 1: Basic grid</title>
<link rel="stylesheet" href="mycss/slick.grid.css" type="text/css"/>
<link rel="stylesheet" href="mycss/smoothness/jquery-ui-1.8.16.custom.css" type="text/css"/>
<link rel="stylesheet" href="mycss/examples.css" type="text/css"/>
</head>
<body>
<div>
<p id="p_title"></p>
<p id="p_duration"></p>
<p id="p_Complete"></p>
<p id="p_start"></p>
<p id="p_finish"></p>
<p id="p_effort-driven"></p>
</div>
<table width="100%">
<tr>
<td valign="top" width="50%">
<div id="myGrid" style="width:600px;height:500px;"></div>
</td>
</tr>
</table>
<script src="js/lib/jquery-1.7.min.js"></script>
<script src="js/lib/jquery.event.drag-2.2.js"></script>
<script src="js/slick.core.js"></script>
<script src="js/slick.grid.js"></script>
<script src="js/slick.dataview.js"></script>
<script>
var grid;
var dataView;
var curr_row;
var curr_cell;
var columns = [
{id: "title", name: "Title", field: "title"},
{id: "duration", name: "Duration", field: "duration"},
{id: "%", name: "% Complete", field: "percentComplete"},
{id: "start", name: "Start", field: "start"},
{id: "finish", name: "Finish", field: "finish"},
{id: "effort-driven", name: "Effort Driven", field: "effortDriven"}
];
var options = {
enableCellNavigation: true,
enableColumnReorder: false
};
$(function () {
var data = [];
for (var i = 0; i < 50; i++) {
data[i] = {
id: i,
title: "Task " + i,
duration: "5 days",
percentComplete: Math.round(Math.random() * 100),
start: "01/01/2009",
finish: "01/05/2009",
effortDriven: (i % 5 == 0)
};
}
dataView = new Slick.Data.DataView();
dataView.setItems(data);
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.onKeyDown.subscribe(function (e, args) {
curr_cell= args.cell;
if (e.which == 38) {
curr_row= args.row - 1;
sata(curr_row)
}
if (e.which == 40){
curr_row = args.row + 1;
sata(curr_row)
}
});
grid.onClick.subscribe(function (e, args){
curr_cell= args.cell;
curr_row = args.row;
sata(curr_row)
});
});
function sata(row){
var row_data = dataView.getItem(row); // Read from dataView not the grid data
var cell_contents = row_data['title'];
alert(cell_contents);
}
$(document).keydown(function(e) {
if (e.which == 38) {
curr_row= curr_row - 1;
grid.gotoCell(curr_row, curr_cell)
grid.onClick.notify({row:curr_row, cell:curr_cell})
}
if (e.which == 40){
curr_row = curr_row + 1;
grid.gotoCell(curr_row, curr_cell)
grid.onClick.notify({row:curr_row, cell:curr_cell}, e)
}
});
</script>
</body>
</html>
Please advice, if there is a better way to achieve this.

Related

Make Ammap from json url

I try make Turkey Map with balloon text. Console does not give an error, but the graph is not drawn.I thought I should first count the provinces of turkey country. I created a variable called number for this. My rules come from the variable json file as "nufusakayıtılil" name. What is wrong? How have to ı fix my code? A
This is my script:
var data = jQuery.getJSON("http://localhost:8080/personel", function(geo) {
var ilVeSayilar = {}
var personelilVeSayilar = [];
$.each(data, function(index, item) {
var il = null;
if (item.nufusakayitliolduguil != null && item.nufusakayitliolduguil.length > 2) {
il = item.nufusakayitliolduguil;
if (ilVeSayilar[il] == null) {
ilVeSayilar[il] = 0;
}
ilVeSayilar[il]++;
}
});
//console.log(ilVeSayılar);
$.each(ilVeSayilar, function(index, item) {
newitem = {}
newitem["id"] = index;
newitem["value"] = item;
personelilVeSayilar.push(newitem)
})
var defaultMap = "turkeyLow";
var countryMaps = {
"TR-01": ["ADANA"],
"TR-02": ["ADIYAMAN"],
"TR-03": ["AFYONKARAHİSAR"],
"TR-04": ["AĞRI"],
"TR-68": ["AKSARAY"],
"TR-05": ["AMASYA"],
"TR-06": ["ANKARA"],
"TR-07": ["ANTALYA"],
"TR-75": ["ARDAHAN"],
"TR-08": ["ARTVİN"],
"TR-09": ["AYDIN"],
"TR-10": ["BALIKESİR"],
"TR-74": ["BARTIN"],
"TR-72": ["BATMAN"],
"TR-69": ["BAYBURT"],
"TR-11": ["BİLECİK"],
"TR-12": ["BİNGÖL"],
"TR-13": ["BİTLİS"],
"TR-14": ["BOLU"],
"TR-15": ["BURDUR"],
"TR-16": ["BURSA"],
"TR-17": ["ÇANAKKALE"],
"TR-18": ["ÇANKIRI"],
"TR-19": ["ÇORUM"],
"TR-20": ["DENİZLİ"],
"TR-21": ["DİYARBAKIR"],
"TR-81": ["DÜZCE"],
"TR-22": ["EDİRNE"],
"TR-23": ["ELAZIĞ"],
"TR-24": ["ERZİNCAN"],
"TR-25": ["ERZURUM"],
"TR-26": ["ESKİŞEHİR"],
"TR-27": ["GAZİANTEP"],
"TR-28": ["GİRESUN"],
"TR-29": ["Gümüşhane"],
"TR-31": ["HATAY"],
"TR-33": ["MERSİN"],
"TR-76": ["IĞDIR"],
"TR-32": ["ISPARTA"],
"TR-34": ["İSTANBUL"],
"TR-35": ["İZMİR"],
"TR-46": ["KAHRAMANMARAŞ"],
"TR-78": ["KARABÜK"],
"TR-70": ["KARAMAN"],
"TR-36": ["KARS"],
"TR-37": ["KASTAMONU"],
"TR-38": ["KAYSERİ"],
"TR-79": ["KİLİS"],
"TR-71": ["KIRIKKALE"],
"TR-39": ["KIRKLARELİ"],
"TR-40": ["KIRŞEHİR"],
"TR-41": ["KOCAELİ"],
"TR-42": ["KONYA"],
"TR-43": ["KÜTAHYA"],
"TR-44": ["MALATYA"],
"TR-45": ["MANİSA"],
"TR-47": ["MARDİN"],
"TR-48": ["MUĞLA"],
"TR-49": ["MUŞ"],
"TR-50": ["NEVŞEHİR"],
"TR-51": ["NİĞDE"],
"TR-52": ["ORDU"],
"TR-80": ["OSMANİYE"],
"TR-53": ["RİZE"],
"TR-54": ["SAKARYA"],
"TR-55": ["SAMSUN"],
"TR-63": ["ŞANLIURFA"],
"TR-56": ["SİİRT"],
"TR-57": ["SİNOP"],
"TR-73": ["ŞIRNAK"],
"TR-58": ["SİVAS"],
"TR-59": ["TEKİRDAĞ"],
"TR-60": ["TOKAT"],
"TR-61": ["TRABZON"],
"TR-62": ["TUNCELİ"],
"TR-64": ["UŞAK"],
"TR-65": ["VAN"],
"TR-77": ["YALOVA"],
"TR-66": ["YOZGAT"],
"TR-67": ["ZONGULDAK"],
};
// calculate which map to be used
var currentMap = defaultMap;
var titles = [];
if (countryMaps[geo.country_code] !== undefined) {
currentMap = countryMaps[geo.country_code][0];
// add country title
if (geo.country_name) {
titles.push({
"text": geo.country_name
});
}
}
var map = AmCharts.makeChart("chartdiv", {
"type": "map",
"theme": "light",
"colorSteps": 10,
"dataProvider": {
"mapURL": "/lib/3/maps/js" + currentMap + ".js",
"getAreasFromMap": true,
"zoomLevel": 0.9,
"areas": []
},
"areasSettings": {
"autoZoom": true,
"balloonText": "[[title]]: <strong>[[value]]</strong>"
},
"valueLegend": {
"right": 10,
"minValue": "Az",
"maxValue": "Çok!"
},
"zoomControl": {
"minZoomLevel": 0.9
},
"titles": titles,
"listeners": [{
"event": "init",
"method": updateHeatmap
}]
});
function updateHeatmap(event) {
var map = event.chart;
if (map.dataGenerated)
return;
if (map.dataProvider.areas.length === 0) {
setTimeout(updateHeatmap, 100);
return;
}
for (var i = 0; i < map.dataProvider.areas.length; i++) {
map.dataProvider.areas[i].value = Math.round(Math.random() * 10000);
}
map.dataGenerated = true;
map.validateNow();
}
});
<title>map created with amCharts | amCharts</title>
<script type="text/javascript" src="https://www.amcharts.com/lib/3/ammap.js"></script>
<link rel="stylesheet" href="http://www.ammap.com/lib/3/ammap.css" type="text/css">
<script type="text/javascript" src="https://www.amcharts.com/lib/3/maps/js/turkeyLow.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>
<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<link rel="shortcut icon" href="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="margin: 0;background-color: rgba(80,80,80,1);">
<div id="map" style="width: 100%; height: 662px;"></div>

Filtering items with angular js

I have an array of items in form of service - as I know it's like proper way to keep data you use in different controllers.I watched tutorial and did the filtering by brands. But I have an obstacle with filtering of my Items by another parameters, such as price, length and frequency... So I have made sliders by another example but I have no idea how to tie up it with my array of Items. Please do me a favour, show how to tie up even one of my parameters, price for example.
http://angular.zxcvbn.ru
services.js:
myApp.service('ProductDataService', function() {
//sample data
var items = [
{ name:'Picachoo', id:1, price:25000, pict:'http://www.metrord.do/_internal/gxml!0/2qijkhn0ctpwx8acoz5fxkpvtmr4nbh$r05jcw5nnz5dt1u7odn7q01jm5k3ezo/screen-shot-2016-07-24-at-11-55-41-am.jpeg', len: 250, friq: 5000, brand: 'came' },
{ name:'Tortule', id:2, price:30000, pict:'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcR2APj6_uBfhHRXLn1dZN58ZocpzMxGMFLZmuqHEU5SybKN4QAVfg', len: 250, friq: 300, brand: 'came' },
{ name:'Dragon', id:3, price:33500, pict:'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSJotIxkjgXgm9m3m-0FuUxN6g9fGGXmP84VDRrPZoWa-x8Dqqd', len: 350, friq: 300, brand: 'came' },
{ name:'encrypted1', id:4, price:45000, pict:'http://gaidi.ru/wp-content/uploads/2016/07/kak-pravilno-lovit-pokemonov-v-pokemon-go.jpg', len: 400, friq: 3000, brand: 'came' },
{ name:'pravilno', id:5, price:48600, pict:'http://vignette3.wikia.nocookie.net/pokemon/images/2/2e/009Blastoise_Dream.png/revision/latest?cb=20140812050618', len: 550, friq: 2000, brand: 'came' },
{ name:'images', id:6, price:30000, pict:'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSqywi0lMtmf1sAR-20rg0HXETMueY3H71iJP35WsdsPHGVokK41g', len: 550, friq: 1000, brand: 'bft' },
{ name:'Foxy', id:7, price:38000, pict:'http://vgtimes.ru/uploads/posts/2016-07/1468938437_pk_vulpix.png', len: 350, friq: 10000, brand: 'bft' },
{ name:'Pteradactys', id:8, price:43000, pict:'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRJBXypwhl8-z4IsAZokgQlqPx_vZymtENBdlPy1HhN34uODEZ5', len: 800, friq: 10000, brand: 'bft' },
{ name:'encrypted', id:9, price:35800, pict:'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQZNKoA9LMtQHhgU4Toy7xXfzGEp6Rb4Kv6I16RgMjWO0Dnb36EFA', len: 1200, friq: 3000, brand: 'faac' },
{ name:'Jidjfj', id:10, price:14000, pict:'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRPBKrRLvhYm9y-LxwRM4Qc_psMjd_luij_04ChmmQjcrdxgmcG3w', len: 800, friq: 5000, brand: 'fors' }
];
brands = {came : true, bft : true, faac : true, fors : true} ;
this.getItems = function() {
return items;
};
this.getBrands = function() {
return brands;
};
this.maxPrice = function() {
var max;
var producto;
for(var i = 0; i < items.length-1; i++) {
for(var j = 0; j < items.length-i-1; j++){
if (producto[j] > producto[j+1]) {
max = producto[j];
producto[j] = producto[j+1];
producto[j+1] = b;
}
}
}
return max;
}
this.minPrice = function() {
var min;
var producto;
for(var i = 0; i < items.length-1; i++) {
for(var j = 0; j < items.length-i-1; j++){
if (producto[j] < producto[j+1]) {
min = producto[j];
producto[j] = producto[j+1];
producto[j+1] = b;
}
}
}
return min;
}
});
slider_price.js:
myApp.controller('priceCtrl', function($scope, ProductDataService) {
$scope.search = { price_min : '', price_max : '', amount_min : 14000, amount_max : 48600 };
});
/* Range Slider
Input with default values:
-min=0 // Min slider value
-max=100 // Max slider value
-step=1 // Steps
Output / Input model
-value-min // Default value #min
-value-max // Default value #max
example:
<slider-range min="0" max="100" step="5" value-min="scope.form.slider_value_min" value-max="scope.form.slider_value_max"></slider-range>
*/
myApp.directive('priceRange', ['$document',function($document) {
// Move slider handle and range line
var moveHandle = function(handle, elem, posX) {
$(elem).find('.handle.'+handle).css("left",posX +'%');
};
var moveRange = function(elem,posMin,posMax) {
$(elem).find('.range').css("left",posMin +'%');
$(elem).find('.range').css("width",posMax - posMin +'%');
};
return {
template: '<div class="slider horizontal">'+
'<div class="range"></div>'+
'<a class="handle min" ng-mousedown="mouseDownMin($event)"></a>'+
'<a class="handle max" ng-mousedown="mouseDownMax($event)"></a>'+
'</div>',
replace: true,
restrict: 'E',
scope:{
valueMin:"=",
valueMax:"="
},
link: function postLink(scope, element, attrs) {
// Initilization
var dragging = false;
var startPointXMin = 0;
var startPointXMax = 0;
var xPosMin = 0;
var xPosMax = 0;
var settings = {
"min" : (typeof(attrs.min) !== "undefined" ? parseInt(attrs.min,10) : 0),
"max" : (typeof(attrs.max) !== "undefined" ? parseInt(attrs.max,10) : 100),
"step" : (typeof(attrs.step) !== "undefined" ? parseInt(attrs.step,10) : 1)
};
if ( typeof(scope.valueMin) == "undefined" || scope.valueMin === '' )
scope.valueMin = settings.min;
if ( typeof(scope.valueMax) == "undefined" || scope.valueMax === '' )
scope.valueMax = settings.max;
// Track changes only from the outside of the directive
scope.$watch('valueMin', function() {
if (dragging) return;
xPosMin = ( scope.valueMin - settings.min ) / (settings.max - settings.min ) * 100;
if(xPosMin < 0) {
xPosMin = 0;
} else if(xPosMin > 100) {
xPosMin = 100;
}
moveHandle("min",element,xPosMin);
moveRange(element,xPosMin,xPosMax);
});
scope.$watch('valueMax', function() {
if (dragging) return;
xPosMax = ( scope.valueMax - settings.min ) / (settings.max - settings.min ) * 100;
if(xPosMax < 0) {
xPosMax = 0;
} else if(xPosMax > 100) {
xPosMax = 100;
}
moveHandle("max",element,xPosMax);
moveRange(element,xPosMin,xPosMax);
});
// Real action control is here
scope.mouseDownMin = function($event) {
dragging = true;
startPointXMin = $event.pageX;
// Bind to full document, to make move easiery (not to lose focus on y axis)
$document.on('mousemove', function($event) {
if(!dragging) return;
//Calculate handle position
var moveDelta = $event.pageX - startPointXMin;
xPosMin = xPosMin + ( (moveDelta / element.outerWidth()) * 100 );
if(xPosMin < 0) {
xPosMin = 0;
} else if(xPosMin > xPosMax) {
xPosMin = xPosMax;
} else {
// Prevent generating "lag" if moving outside window
startPointXMin = $event.pageX;
}
scope.valueMin = Math.round((((settings.max - settings.min ) * (xPosMin / 100))+settings.min)/settings.step ) * settings.step;
scope.$apply();
// Move the Handle
moveHandle("min", element,xPosMin);
moveRange(element,xPosMin,xPosMax);
});
$document.mouseup(function(){
dragging = false;
$document.unbind('mousemove');
$document.unbind('mousemove');
});
};
scope.mouseDownMax = function($event) {
dragging = true;
startPointXMax = $event.pageX;
// Bind to full document, to make move easiery (not to lose focus on y axis)
$document.on('mousemove', function($event) {
if(!dragging) return;
//Calculate handle position
var moveDelta = $event.pageX - startPointXMax;
xPosMax = xPosMax + ( (moveDelta / element.outerWidth()) * 100 );
if(xPosMax > 100) {
xPosMax = 100;
} else if(xPosMax < xPosMin) {
xPosMax = xPosMin;
} else {
// Prevent generating "lag" if moving outside window
startPointXMax = $event.pageX;
}
scope.valueMax = Math.round((((settings.max - settings.min ) * (xPosMax / 100))+settings.min)/settings.step ) * settings.step;
scope.$apply();
// Move the Handle
moveHandle("max", element,xPosMax);
moveRange(element,xPosMin,xPosMax);
});
$document.mouseup(function(){
dragging = false;
$document.unbind('mousemove');
$document.unbind('mousemove');
});
};
}
};
}]);
app.js:
var myApp = angular.module("filterApp", []);
myApp.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$scope.greeting = 'Hello, World!';
$scope.doGreeting = function(greeting) {
$window.alert(greeting);
};
}]);
myApp.controller('coolCtrl', function($scope) {
$scope.whoAmI = function(){
console.log("This is whoAmI function in the coolCtrl!");
};
});
myApp.controller('mainCtrl', function($scope, ProductDataService){
$scope.helloWorld = function(){
console.log("This is helloWorld function in the mailCtrl!");
};
$scope.items = ProductDataService.getItems();
$scope.brands = ProductDataService.getBrands();
$scope.refresh = function(){
location.reload();
};
$scope.showPopUpMsg = false;
$scope.openPopUp = function( text ) {
$scope.showPopUpMsg = true;
$scope.popUpMsgContent = text;
$scope.minimun = 123;
};
});
jilters.js:
myApp.filter('brandsfilter', function () {
return function(input, filter) {
var result = [];
angular.forEach(input, function (item) {
angular.forEach(filter, function (isfiltered, brand) {
if (isfiltered && brand === item.brand) {
result.push(item);
}
});
});
return result;
};
});
index.php:
<?php
require 'scripts/mail_script.php';
?>
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="styles/normalize.css">
<link rel="stylesheet" href="styles/main.css">
<link rel="stylesheet" href="styles/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!-- for slider work -->
</head>
<body ng-app="filterApp" ng-controller='mainCtrl'>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please upgrade your browser to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class="container">
<section class='top' >
<h1>Filter</h1>
<!-- //// http://embed.plnkr.co/woqn3i/ /// -->
<!-- ///////// -->
<div class="row" id='items'>
<div>
<div class="col-md-4" ><h2>params:</h2>
<div ng-controller="priceCtrl">
<p>Choose price:</p>
<p>min: <input type="number" ng-model="search.amount_min"/> $</p>
<p>max: <input type="number" ng-model="search.amount_max"/> $</p>
<slider-range min="14000" max="48600" step="100" value-min="search.amount_min" value-max="search.amount_max"></slider-range>
</div>
<hr>
<p>По названию:</p>
<p><input type="text" ng-model="price" /></p>
<p>Brand:</p>
<ul >
<li ng-repeat="(brand, value) in brands">
<input type="checkbox" ng-model="brands[brand]" /> {{brand}}
</li>
</ul>
<hr>
<!-- //// http://embed.plnkr.co/woqn3i/ /// -->
<div ng-controller="filterCtrl">
<p>length:</p>
<p>От: <input type="text" ng-model="search.price_min"/> meters</p>
<p>До: <input type="text" ng-model="search.price_max"/> meters</p>
<slider-range min="2.5" max="12" value-min="search.price_min" value-max="search.price_max"></slider-range>
<hr>
<p>friquincy:</p>
<p>Min: <input type="number" ng-model="search.amount_min"/> times</p>
<p>Max: <input type="number" ng-model="search.amount_max"/> times</p>
<slider-range min="300" max="10000" step="100" value-min="search.amount_min" value-max="search.amount_max"></slider-range>
</div>
<hr>
<!-- ///////// -->
<div class="actions"/>
<input type="button" value="Сбросить" ng-click='refresh()'>
</div>
</div>
<div class="col-md-8"><h2>______ kinds</h2>
<?php
if($success) echo '<h4 class="bg-success text-center">'.'Сообщение отправлено!' . '</h4>';
if($error_message) echo '<h4 class="bg-danger text-center">'.'Сообщение не отправлено:' . $error_message. '</h4>';
?>
<div class="row">
<!-- LOOP.-->
<div ng-repeat="item in items | filter:price | orderBy:price | brandsfilter:brands ">
<div class="col-md-4 col-sm-6 col-sx-12">
<div class="item-inner">
<div class="image-product">
<div class="caption">
<div class="box-view">
<div class="name">{{item.name}}</div>
</div>
</div>
<img src="{{item.pict}}" alt="{{item.name}}" title="{{item.name}}" class="img-responsive">
<p class="price"><span class="price">Price: {{item.price}} $.</span></p>
<p class="description">{{item.name}} - just another piece of information, first preporty is {{item.len}} m. <br>another is: {{item.friq}} per day. </p>
</div>
</div>
</div><!-- col -->
</div> <!-- ng-repeat -->
</div> <!-- row -->
</div>
</div> <!-- mainCtrl -->
</section>
</div>
<div class="panel-footer">
<script src="vendor/angular.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/services.js"></script>
<script src="scripts/filters.js"></script>
<script src="scripts/slider.js"></script>
<script src="scripts/slider_price.js"></script>
<script src="vendor/jquery.js"></script>
<script src="vendor/bootstrap.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
</div>
</body>
</html>
AngularJS built-in filter which you already used supports multiple keywords filter see, you only need to implement comparator function to fulfill your needs.
First, change your filter in template to
<div ng-repeat="item in items | filter:myFilters:myComparator | orderBy:price">
then inside your filterCtrl you need to define myFilters and myComparator
$scope.myFilters = {price: 4000, brand: 'abc'};
$scope.myComparator = function(actual, expected) {
if (actual == parseInt(actual)) {
return actual > expected;
}
else {
return actual == expected;
}
}
Inside myComparator you can customise how you want to filter it (exact match, arithmetic comparison or partial match, just remember to return Boolean.
Just update $scope.myFilters whenever your filter keywords changed, the result will be updated in next digest cycle.

show item position in list created with json during/after sorting using Sortable

I have a list generated with json, and it's sortable with RubaXa/Sortable plugin.
I need to add the item position in the list while sorting the list. So when moving an item up or down the item position indicators will change.
I commented some lines with the issue.
Sortable function:
var listPos;
Sortable.create(list-group, {
handle: '.driver',
animation: 150,
onMove: function (evt) {
evt.dragged;
evt.draggedRect;
evt.related;
evt.relatedRect;
listPos = $(this).closest('.list-group').children('.list-group-item').index(this); // error finding the position in the list
console.log(evt); // event is shown in the console
console.log(listPos); // this is showing always -1 after the event
}
});
The json:
[
{
"name": "item 1",
"acr": "it1"
},
{
"name": "item 2",
"acr": "it2"
},
{
"name": "item 3",
"acr": "it3"
},
{
"name": "item 4",
"acr": "it4"
}
]
The HTML:
<div class="col-md-4">
<div id="printList" class="list-group">
</div>
</div>
Parsing/Printing the json:
var xmlhttp = new XMLHttpRequest();
var url = "/list.json";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
showListPos = listPos; // showListPost in undefined
var arr = JSON.parse(response);
var i;
var out = "";
var drawPos = "<div class='position'>" + showListPos + "</div>"; //
for (i = 0; i < arr.length; i++) {
out += "<div class='list-group-item'>" +
"<p>" + drawPos + "</p>"
"<h3><span>" + arr[i].name + "</span>" +
arr[i].acr +
"</h3></div>";
}
out += "";
document.getElementById("printList").innerHTML = out;
}
to get the moved item position while moving it,you can use onEnd event instead onMove.in onEnd you can access position using evt.newIndex.check the below snippet
Sortable.create(sortTrue, {
group: "sorting",
sort: true,
onEnd: function(evt) {
$(evt.item).parent().find('.list-group-item').each(function() {
$(this).find('span').text($(this).index() + 1);
});
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="result">Drage the list item to see position</div>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<!-- Latest Sortable -->
<script src="http://rubaxa.github.io/Sortable/Sortable.js"></script>
<!-- sort: true -->
<div id="sortTrue" class="list-group">
<div class="list-group-item"><span>1</span> foo</div>
<div class="list-group-item"><span>2</span> bar</div>
<div class="list-group-item"><span>3</span> baz</div>
<div class="list-group-item"><span>4</span> qux</div>
<div class="list-group-item"><span>5</span> quux</div>
</div>
</body>
</html>

Unable to draw Spline on secondary Y Axis (getting data from CSV file) using highchart

I am new to Highcharts and trying to draw a graph by reading a CSV File. when i extract and try to display i see that the values of the Y Axis are dots on one line (Vertical) instead of a horizontal Line.
Please tell me how to convert it to secondary X-Axis.
My Entire Code:
data.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Performance Dashboard</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="C:\Project\datafromCSV\js\jquery.min.js"></script>
<script type="text/javascript" src="C:\Project\datafromCSV\scripts\highcharts.js"></script>
<!--<link rel="stylesheet" type="text/css" href="C:\strawberry\files\styles\dbdash.css" />
<link rel="stylesheet" type="text/css" href="C:\Project\strawberry files\css\jmenu.css" />
-->
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
function load()
{
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: '5 min interval'
},
xAxis: {
categories: []
},
yAxis:[{
startOnTick: false,
title: {
text: 'No of Transactions'
}
},
{
opposite: true,
title: {
text: 'Response Time'
}
}
],
series: []
};
$.get('timeData.csv', function(data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
// header line contains categories
if (lineNo == 0) {
$.each(items, function(itemNo, item) {
if (itemNo > 0) options.xAxis.categories.push(item);
});
}
// the rest of the lines contain data with their name in the first position
else {
var series = {
data: []
};
var series1 = {
yAxis:1,
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
}
else if (itemNo == 2) {
series1.name='Response time';
series1.type = 'spline';
series1.data.push(parseFloat(item));
}
else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
options.series.push(series1);
}
});
var chart = new Highcharts.Chart(options);
});
});
}
function funCPU()
{
alert("hi");
}
</script>
</head>
<body id="dbdashBody" onload="load()">
<table class="container" border="0" align="center" cellpadding=0 cellspacing=0>
<tr>
<td valign="top">
<div class="header">
<div class="headerLeft">
</div>
<div class="headerCenter"><img src="C:\strawberry\files\images\logo.jpg"/>
<font color="#3366FF"><i><b>TIERS PERFORMANCE DASHBOARD</b></i></font>
<div class="loaderGif"> </div>
</div>
<div class="headerRight">
</div>
</div>
<div class="menuBar">
<ul id="jMenu">
<li><a href="#" ><b>Home Page</b></a></li>
<li><b>CPU Utilization</b></li>
</ul>
</td>
</tr>
</table>
<!-- 3. Add the container -->
<div id="container" style="width:1200px; height:400px; vertical-align: top; display: inline-block; padding: 10px;"></div>
</body>
</html>
and timeData.csv
Time,users,AverageSec,Volume
8:00,2325,0.627,28821
7:55,1529,0.609,19124
7:50,1095,0.544,15825
7:45,865,0.584,12852
7:40,709,0.573,10263
7:35,554,0.605,8149
7:30,427,0.641,5821
Please need help and its greatly appreciated!!!
Thanks a lot in advance.
Is this what you want? Fiddle: http://jsfiddle.net/Yrygy/84/
I have created three axis, each for one column in your data, where first column is category - time. First create series, otherwise you will create series for each line (you already doing this). After series are created push items from a line to specifc series, and in laste step, before creating chart - push series to options.
var data = 'Time,users,AverageSec,Volume\n8:00,2325,0.627,28821\n7:55,1529,0.609,19124\n7:50,1095,0.544,15825';
// Split the lines
var lines = data.split('\n');
var series = {
data: []
};
var series1 = {
yAxis: 1,
data: [],
type: 'spline'
};
var series2 = {
yAxis: 2,
data: []
};
$.each(lines, function (lineNo, line) {
var items = line.split(',');
// header line contains names
if (lineNo == 0) {
series1.name = items[1];
series.name = items[2];
series2.name = items[3];
/*$.each(items, function (itemNo, item) {
if (itemNo > 0)
series.name = item;
});*/
}
// the rest of the lines contain data with their name in the first position
else {
$.each(items, function (itemNo, item) {
// first item on line - category/time
if (itemNo == 0) {
options.xAxis.categories.push(item);
} else if (itemNo == 1) {
series1.data.push(parseFloat(item));
} else if(itemNo == 2){
series.data.push(parseFloat(item));
} else if(itemNo == 3){
series2.data.push(parseFloat(item));
}
});
}
});
options.series.push(series);
options.series.push(series1);
options.series.push(series2);
var chart = new Highcharts.Chart(options);

How to prevent selected index from changing when bound data changes?

Using knockout, I have a select (a list of names) whose options are bound to another set of knockout-bound data (people). When the name of any person changes, the value of the select option that is bound to that person's name is correctly updated. However, the select's selection is not preserved if you had that person selected already.
See this jsFiddle for a live example: http://jsfiddle.net/DbBZQ/
Select "Jane" from the list.
Change the name "Jane" to something else ("Jane Doe" for example).
Notice the select defaults back to the first item.
How can I make the selection stick to the same option index even if the underlying value has changed? Is there a way to instruct knockout to preserve the selection or do I have to do this separately using JS?
Complete Code Example
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var data =
{
people: ko.observableArray(
[
{ name: ko.observable("Jim") },
{ name: ko.observable("Jane") },
{
name: ko.observable("Sam"),
subordinates: ko.observableArray(
[
{
name: ko.observable("Tambone"),
subordinates: ko.observableArray(
[
{ name: ko.observable("Edward") },
{ name: ko.observable("Kristy") },
{ name: ko.observable("Thomas") },
{ name: ko.observable("Andy") }
])
},
{ name: ko.observable("Jules") }
])
}
])
};
var allNames = ko.computed(function ()
{
var names = [];
var selector = function (name, indent)
{
var option =
{
value: name,
text: (indent || "") + name
};
return option;
};
for (var i = 0; i < data.people().length; i++)
{
names.push(selector(data.people()[i].name()));
addSubordinates(names, 1, data.people()[i].subordinates, selector);
}
return names;
});
function addSubordinates(names, depth, subordinates, selector)
{
if (subordinates != null)
{
var indentText = "";
for (var i = 0; i < depth; i++)
indentText += ". . ";
for (var i = 0; i < subordinates().length; i++)
{
names.push(selector(subordinates()[i].name(), indentText));
addSubordinates(names, depth + 1, subordinates()[i].subordinates, selector);
}
}
}
</script>
</head>
<body>
<div data-bind="foreach: data.people">
<input type="text" data-bind="value: name" /><br />
</div>
Add Person
<br /><br /><br />
<select data-bind="options: allNames, optionsValue: 'value', optionsText: 'text', optionsCaption: 'All Names...'" />
<script type="text/javascript">
ko.applyBindings();
</script>
</body>
</html>
The reason the selection is lost is because the selected value is matched directly to the name property, which changes. As a result, the selected value no longer exists in the data source (allNames).
If you want to retain the selection, you have a couple of options:
Implement a hack such as tracking the index, and resetting it after the value changes
Bind the selected value to a property that doesn't change.
Do you have an immutable property that you can use as the selected value?
For the sake of an example, I added an id property to the objects in the data source, and use that as the selected value instead of name. This works the way you expect:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var data =
{
people: ko.observableArray(
[
{ id: 1, name: ko.observable("Jim") },
{ id: 2, name: ko.observable("Jane") },
{
id: 3, name: ko.observable("Sam"),
subordinates: ko.observableArray(
[
{
id: 4, name: ko.observable("Tambone"),
subordinates: ko.observableArray(
[
{ id: 5, name: ko.observable("Edward") },
{ id: 6, name: ko.observable("Kristy") },
{ id: 7, name: ko.observable("Thomas") },
{ id: 8, name: ko.observable("Andy") }
])
},
{ id: 9, name: ko.observable("Jules") }
])
}
])
};
var allNames = ko.computed(function ()
{
var names = [];
var selector = function (id, name, indent)
{
var option =
{
value: id,
text: (indent || "") + name
};
return option;
};
for (var i = 0; i < data.people().length; i++)
{
names.push(selector(data.people()[i].id, data.people()[i].name()));
addSubordinates(names, 1, data.people()[i].subordinates, selector);
}
return names;
});
function addSubordinates(names, depth, subordinates, selector)
{
if (subordinates != null)
{
var indentText = "";
for (var i = 0; i < depth; i++)
indentText += ". . ";
for (var i = 0; i < subordinates().length; i++)
{
names.push(selector(subordinates()[i].id,subordinates()[i].name(), indentText));
addSubordinates(names, depth + 1, subordinates()[i].subordinates, selector);
}
}
}
</script>
</head>
<body>
<div data-bind="foreach: data.people">
<input type="text" data-bind="value: name" /><br />
</div>
Add Person
<br /><br /><br />
<select data-bind="options: allNames, optionsValue: 'value', optionsText: 'text', optionsCaption: 'All Names...'" />
<script type="text/javascript">
ko.applyBindings();
</script>
</body>
</html>
Edit:
As an alternative, what if you set up the value property so that it was a ko.computed that returned the index of the item? Like this:
var allNames = ko.computed(function ()
{
var names = [];
var selector = function (item, name, indent)
{
var option =
{
value: ko.computed(function(){ return data.people().indexOf(item);}),
text: (indent || "") + name
};
return option;
};
for (var i = 0; i < data.people().length; i++)
{
names.push(selector(data.people()[i], data.people()[i].name()));
addSubordinates(names, 1, data.people()[i].subordinates, selector);
}
return names;
});
function addSubordinates(names, depth, subordinates, selector)
{
if (subordinates != null)
{
var indentText = "";
for (var i = 0; i < depth; i++)
indentText += ". . ";
for (var i = 0; i < subordinates().length; i++)
{
names.push(selector(subordinates()[i],subordinates()[i].name(), indentText));
addSubordinates(names, depth + 1, subordinates()[i].subordinates, selector);
}
}
}

Categories