Labels for tooltips on primefaces barchartseries - primefaces

I have tried to search both the forum and Google extensively, but I have problems understanding how I should make this work:
PrimeFaces6
I have a BarchartModel based on the tutorial in the ShowCase:
CODE: SELECT ALL
private BarChartModel initStatusBarChart() {
BarChartModel model = new BarChartModel();
ChartSeries statusMessages = new ChartSeries();
statusMessages.setLabel("Label"));
statusMessages.set("Some String 1", list1.size());
statusMessages.set("Some String 2", list2.size());
model.addSeries(statusMessages);
return model;
}
The issue is that on render, I get tooltips the format of
"1, 515" and "2, 432", where 515 and 432 are the sizes of list1 and list2, respectively.
How can I replace 1 and 2 with the values "Some String" 1 and 2 ? Have tried extending highlighter and using dataTipFormat, with no success.

I solved the problem using the datatip editor of the chart model (with Primefaces 6.1, by the way). I used this for a stacked bar chart.
I needed to apply this solution at two places: the backing bean and the JSF page.
In the backing bean I had to set a JavaScript function name this way:
barModel.setDatatipEditor("chartDatatipEditor");
I tried to set it using the corresponding tag attribute in the JSF page but to no effect.
In the JSF I inserted this JavaScript code:
<script type="text/javascript">
function chartDatatipEditor(str, seriesIndex, pointIndex, plot) {
//console.log('chartDatatipEditor: '+str+" - "+seriesIndex+" - "+pointIndex);
var point = seriesIndex+','+pointIndex;
#{bean.datatipsJs}
}
</script>
This JS function gets the chart coordinates as parameters. I concat them so that the following JS code gets easier.
seriesIndex is the index of the chart series. pointIndex is the index on the X scale of the diagram.
To find out what are the correct values for your chart you can uncomment the console.log line above.
The inserted JS code is constructed in the backing bean this way:
private Map<String, String> chartDatatips;
public String getDatatipsJs() {
StringBuilder sb = new StringBuilder("switch ( point ) {\n");
for (String point : chartDatatips.keySet()) {
sb.append("case '").append(point).append("': return '").append(chartDatatips.get(point)).append("'; break;\n");
}
sb.append("default: return 'Unknown point'; break; }");
return sb.toString();
}
The map chartDatatips has the coordinate point as key (e.g., "2,1") and the tooltip as value.
During the chart setup you obviously have to fill this map with useful details ;-)
Like this:
chartDatatips.put("2,5", "Label ...");
...
Hope this helps, if you didn't already solved this.
~Alex

Based on Alex's answer I have come up with this. Only requiring javascript - it displays the label and value:
In the backing bean, set a JavaScript function name this way:
barModel.setDatatipEditor("chartDatatipEditor");
In the HTML file:
function chartDatatipEditor(str, seriesIndex, pointIndex, plot) {
return plot.series[seriesIndex].label + ' - ' + plot.data[seriesIndex][pointIndex];
}

Related

How to handle $ctrl. in AngularJS?

I have a Methode from an API. It returns a promise which resolves to an $ctrl(?) object. This objects should contain a measurement and will be updated whenever it receive a new data.
getMeasurements.latest(filter) //only a object to filter through all measurements
.then(function (latestMeasurement) {
$ctrl.latestMeasurement = latestMeasurement;
});
My problem is that I don't know how to work with this data or display it in my html file. How does $ctrl work?
Here the documentation of the API
$ctrl is the view model object in your controller. This $ctrl is a name you choose (vm is another most common name), if you check your code you can see the definition as $ctrl = this;, so basically its the this keyword of the controller function.
So now if you are using $ctrl.latestMeasurement = 'someValue', then its like you are adding a property latestMeasurement to controller function.
Now how to use it in HTML?
To access the latestMeasurement property in HTML your code must have <h1>{{$ctrl.latestMeasurement}}</h1> (H1 tag is just an example.)
Here $ctrl is different from what I explained above on controller part. Here $ctrl is the value used for controllerAs property of the controller. But $ctrl is the default value of the controllerAs property, so your code may not have the controllerAs property defined, so Angular will take default value $ctrl in HTML.
This is where most people gets confused. So let me explain,
Assume in your new controller you have declared your this keyword to variable vm, and you set your controllerAs property to myCtrl, i.e;
controllerAs: 'myCtrl' while defining controller properties.
var vm = this; in your controller function.
In this case in js you have to use vm for setting values, and in HTML you have to use myCtrl. For example,
in JS controller function vm.test = 'Hello world';
in HTML <span ng-bind="myCtrl.test"></span>
The result Hello world will be displayed in your page.
Why $ctrl and not $scope?
The view model object model concept is introduced in AngularJS 1.5, it is actually part of migrating to Angular 2 where $scope no longer exsist. So in 1.5 they introduced new approch but did not removed $scope completely.
Hope the answer helped.
For basic Javascript concepts you can see http://javascriptissexy.com/16-javascript-concepts-you-must-know-well/
For more detailed AngularJS $ctrl concept you can see https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/
I suppose you are toking about this.
In this case, the
$ctrl.latestMeasurement
can means:
$ctrl, the controller where you are running this code. You can change it by $scope for example, and get the same result.
latestMeasurement, the variable where you want to store the last value of the measurement.
To explain my point of view let see the code below
<div ng-app="MeasurementApp">
<div ng-controller="MeasurementController">
<h1>{{latestMeasurement2}}</h1>
</div>
</div>
There you can see a simple angularjs app that shows a variable called latestMeasurement2 in a div and its controller called MeasurementController. Then, to display the value let check your code.
angular.module('MeasurementApp', [])
// creating the controller
.controller('MeasurementController', function(c8yMeasurements, $scope) {
// creating the variable and let it empty by now.
$scope.latestMeasurement2 = "";
// Your code
var filter = {
device: 10300,
fragment: 'c8y_Temperature',
series: 'T'
};
var realtime = true;
c8yMeasurements.latest(filter, realtime)
.then(function (latestMeasurement) {
// The latestMeasurement is where the measurement comes
// Here we just assign it into our $scope.latestMeasurement2
$scope.latestMeasurement2 = latestMeasurement;
});
});
As the documentation says
// $scope.latestMeasurement2 will be updated as soon as a new measurement is received.
$scope.latestMeasurement2 = latestMeasurement;
Hope this helps!

Creating new objects for select dropdowns in Angular

This is a simplified version of my problem, as my model is much bigger.
I'm generating a drop-down from a set of objects, and using the object.Name property of each to fill the select.
<md-select [(ngModel)]="selectedDetachment" placeholder="Select a detachment">
<md-option *ngFor="let option of detachmentOptions" [value]="option">
{{option.Name}}
</md-option>
</md-select>
the detachmentOptions object is a generated set of 3 objects, all of which extend Detachment,
private detachmentOptions: Detachment[];
this.detachmentOptions = [
new DetachmentPatrol(),
new DetachmentBattalion(),
new DetachmentBrigade()
];
I want to add a detachment to my main army, based on the select, which uses the following function
addDetachment() {
if(this.selectedDetachment) {
this.army.Detachments.push(this.selectedDetachment.constructor());
// this.makeDetachmentOptions();
}
}
My problem is that this uses the orignal, as JS inherantly passes by reference. No matter how many copies of DetachmentBattaliion I add, they all contain the same contents, as they are each references to the original created in the constructor.
I need to be able to create a brand-new blank object of the type selected, and I'm completely blanking on how to do this.
Object.prototype() gets the prototype, so I can't get the type, and I can't find a way to use typeof to genearate a new copy of the object.
It does not need to copy the object wholesale, I just need a method of creating the original type, without tying them together by reference.
You can use lodash's cloneDeep. It creates a new object instance instead of referencing the same object.
import { cloneDeep } from 'lodash';
...
export class ... {
private detachmentOptions: Detachment[];
...
addDetachment() {
if(this.selectedDetachment) {
const selectedDetachment = cloneDeep(this.selectedDetachment);
this.army.Detachments.push(selectedDetachment.constructor());
// this.makeDetachmentOptions();
}
}
}
you may try below,
addDetachment() {
if(this.selectedDetachment) {
const prototype = Object.getPrototypeOf(this.selectedDetachment);
const instance = Object.create(prototype);
this.army.Detachments.push(instance);
console.log(instance);
console.log(this.army);
}
}
Check this Plunker!!

iOS DatePicker binding gives MvxBind:Error for viewmodel => view direction

I am using an iOS UIDatepicker (weekendOnTimepick) in 'time only'mode in one of my views that needs to update the properties in my Viewmodel whenever the Picker view is changed. The direction Viewmodel => view is only important at View load hence is treated outside of the binding (see code below).
Although this works great (after overcoming the challenges of iOS wrt time localisation), I get a message "MvxBind:Error: 86.61 Problem seen during binding execution for binding Time for TimerOnWeekend - problem ArgumentException: Object type System.DateTime cannot be converted to target type: MonoTouch.Foundation.NSDate"
I guess this has to do with the binding direction I'm not using and doesn't seem to be an issue, but I do fear it will bring some sort of instability to my app.
Question : is this the right way of achieving the goal stated above, or would it be better to for instance ditch binding alltogether and use a View to Viewmodel subscription message with every Datepicker update ?
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
_userSettings = Mvx.Resolve<IHpRepository>().HpFullData.UserSettings;
var set = this.CreateBindingSet<TimerView, TimerViewModel>();
// TODO: check timepicker binding
set.Bind(weekendOnTimepick).For("Time").To(vm => vm.TimerOnWeekend);
int weekendOnHr = _userSettings.TimerOnWeekend / 3600 ;
int weekendOnMin = (_userSettings.TimerOnWeekend % 3600) / 60;
var weekendOnTime = new DateTime (2014, 1, 1, weekendOnHr, weekendOnMin, 0);
var AdjweekendOnTime = weekendOnTime.ToUniversalTime ();
weekendOnTimepick.SetDate (TouchConverter.DateTimeToNSDate(AdjweekendOnTime),true);
set.Apply();
}

Special JSON binding in WinJS ListView

I have problems binding this JSON to my list view.
http://pubapi.cryptsy.com/api.php?method=marketdatav2
No data is displayed.
Data.js
(function () {
"use strict";
var _list;
WinJS.xhr({ url: 'http://pubapi.cryptsy.com/api.php?method=marketdatav2' }).then(
function (response) {
var json = JSON.parse(response.responseText);
_list = new WinJS.Binding.List(json.return.markets);
},
function (error) {
//handle error
}
);
var publicMembers =
{
itemList: _list
};
WinJS.Namespace.define("DataExample", publicMembers);
})();
HTML:
<section aria-label="Main content" role="main">
<div id="listItemTemplate" data-win-control="WinJS.Binding.Template">
<div class="listItem">
<div class="listItemTemplate-Detail">
<h4 data-win-bind="innerText: label"></h4>
</div>
</div>
</div>
<div id="listView" data-win-control="WinJS.UI.ListView" data-win-options="{itemDataSource : DataExample.itemList, itemTemplate: select('#listItemTemplate'), layout: {type: WinJS.UI.GridLayout}}"></div>
</section>
I feel that the API is not that well formed.
Isnt this part a bit odd?
"markets":{"ADT/XPM":{...}...}
There are three things going on in your code here.
First, a ListView must be bound to a WinJS.Binding.List's dataSource property, not the List directly. So in your HTML you can use itemDataSource: DataExample.itemList.dataSource, or you can make your DataExample.itemList dereference the dataSource at that level.
Second, you're also running into the issue that the declarative binding of itemDataSource in data-win-options is happening well before DataExample.itemList is even populated. At the point that the ListView gets instantiated, _list and therefore itemList will be undefined. This causes a problem with trying to dereference .dataSource.
The way around this is to make sure that DataExample.itemList is initialized with at least an empty instance of WinJS.Binding.List on startup. So putting this and the first bit together, we have this:
var _list = new WinJS.Binding.List();
var publicMembers =
{
itemList: _list.dataSource
};
With this, you can later replace _list with a different List instance, and the ListView will refresh itself.
This brings us to the third issue, populating the List with your HTTP response data. The WinJS.Binding.List takes an array in its constructor, not an object. You're passing the parsed JSON object straight from the HTTP request, which won't work.
Now if you have a WinJS.Binding.List instance already in _list as before, then you can just walk the object and add items directly to the List as follows:
var jm = json.return.markets;
for (var i in jm) {
_list.push(jm[i]);
}
Alternately, you could populate a separate array and then create a new List from that. In this case, however, you'll need to assign that new List.dataSource to the ListView in code:
var jm = json.return.markets;
var markets = [];
for (var i in jm) {
markets.push(jm[i]);
}
_list = new WinJS.Binding.List(markets);
var listview = document.getElementById("listView").winControl;
listview.itemDataSource = _list.dataSource;
Both ways will work (I tested them). Although the first solution is simpler and shorter, you'll need to make sure to clear out the List if you make another HTTP request and repopulate from that. With the second solution you just create a new List with each request and hand that to the ListView, which might work better depending on your particular needs.
Note also that in the second solution you can remove the itemDataSource option from the HTML altogether, and also eliminate the DataExample namespace and its variables because you'll assign the data source in code each time. Then you can also keep _list entirely local to the HTTP request.
Hope that helps. If you want to know more about ListView intricacies, see Chapter 7 of my free ebook from MSPress, Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition.

call code behind functions with html controls

I have a simple function that I want to call in the code behind file name Move
and I was trying to see how this can be done and Im not using asp image button because not trying to use asp server side controls since they tend not to work well with ASP.net MVC..the way it is set up now it will look for a javascript function named Move but I want it to call a function named move in code behind of the same view
<img alt='move' id="Move" src="/Content/img/hPrevious.png" onclick="Move()"/>
protected void Move(){
}
//based on Search criteria update a new table
protected void Search(object sender EventArgs e)
{
for (int i = 0; i < data.Count; i++){
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell CheckCell = new HtmlTableCell();
HtmlTableCell firstCell = new HtmlTableCell();
HtmlTableCell SecondCell = new HtmlTableCell();
CheckBox Check = new CheckBox();
Check.ID = data[i].ID;
CheckCell.Controls.Add(Check);
lbl1.Text = data[i].Date;
lbl2.Text = data[i].Name;
row.Cells.Add(CheckCell);
row.Cells.Add(firstCell);
row.Cells.Add(SecondCell);
Table.Rows.Add(row);
}
}
Scott Guthrie has a very good example on how to do this using routing rules.
This would give you the ability to have the user navigate to a URL in the format /Search/[Query]/[PageNumber] like http://site/Search/Hippopotamus/3 and it would show page 3 of the search results for hippopotamus.
Then in your view just make the next button point to "http://site/Search/Hippopotamus/4", no javascript required.
Of course if you wanted to use javascript you could do something like this:
function Move() {
var href = 'http://blah/Search/Hippopotamus/2';
var slashPos = href.lastIndexOf('/');
var page = parseInt(href.substring(slashPos + 1, href.length));
href = href.substring(0, slashPos + 1);
window.location = href + (++page);
}
But that is much more convoluted than just incrementing the page number parameter in the controller and setting the URL of the next button.
You cannot do postbacks or call anything in a view from JavaScript in an ASP.NET MVC application. Anything you want to call from JavaScript must be an action on a controller. It's hard to say more without having more details about what you're trying to do, but if you want to call some method "Move" in your web application from JavaScript, then "Move" must be an action on a controller.
Based on comments, I'm going to update this answer with a more complete description of how you might implement what I understand as the problem described in the question. However, there's quite a bit of information missing from the question so I'm speculating here. Hopefully, the general idea will get through, even if some of the details do not match TStamper's exact code.
Let's start with a Controller action:
public ActionResult ShowMyPage();
{
return View();
}
Now I know that I want to re-display this page, and do so using an argument passed from a JavaScript function in the page. Since I'll be displaying the same page again, I'll just alter the action to take an argument. String arguments are nullable, so I can continue to do the initial display of the page as I always have, without having to worry about specifying some kind of default value for the argument. Here's the new version:
public ActionResult ShowMyPage(string searchQuery);
{
ViewData["SearchQuery"] = searchQuery;
return View();
}
Now I need to call this page again in JavaScript. So I use the same URL I used to display the page initially, but I append a query string parameter with the table name:
http://example.com/MyControllerName/ShowMyPage?searchQuery=tableName
Finally, in my aspx I can call a code behind function, passing the searchQuery from the view data. Once again, I have strong reservations about using code behind in an MVC application, but this will work.
How to call a code-behind function in aspx:
<% Search(ViewData["searchQuery"]); %>
I've changed the arguments. Since you're not handling an event (with a few exceptions, such as Page_Load, there aren't any in MVC), the Search function doesn't need the signature of an event handler. But I did add the "tablename" argument so that you can pass that from the aspx.
Once more, I'll express my reservations about doing this in code behind. It strikes me that you are trying to use standard ASP.NET techniques inside of the MVC framework, when MVC works differently. I'd strongly suggest going through the MVC tutorials to see examples of more standard ways of doing this sort of thing.