Appending el in Backbone from an instance - backbone.js

I'm attempting to append the html within el from instances
var Article1 = Backbone.View.extend({
initialize: function(options) {
console.log('type 1', options)
this.flyIn(options);
},
flyIn: function(options) {
this.$el.find('.superDog').css({
display: 'block'
});
this.$el.find('.superDog').animate({
top: options.top,
left: options.left
}, 3000);
},
render: function() {
},
el: '<div><p class="superDog"></p></div>'
});
var Article1A = new Article1({
color: 'black',
top: '300',
left: '300',
html: 'hello world'
});
var Article1B = new Article1({
color: 'blue',
top: '800',
left: '800',
html: 'Hello Everyone'
});
var Article1C = new Article1({
color: 'blue',
top: '600',
left: '1000',
html: 'Hello No One'
});
I've tried putting append.el (or el.append, wasn't sure which way it went), options.html, etc.
Is it possible to do what I'm trying to do or do I have to use something else?

Take time to read the Backbone documentation:
the el view property is a string (a selector) or DOM element,
the this.$el refer to a jQuery object of this.el which is the DOM element.
template is whatever you want, a function or a string mostly.
Optimize your use of jQuery by caching objects instead of selecting them over and over.
// chain when possible
this.$('.superDog')
.append(options.html)
.css({ display: 'block' });
// cache the object
var $superDog = this.$('.superDog');
// and use it later
$superDog.append(options.html);
// ...more code and then...
$superDog.css({ display: 'block' });
Rendering a dynamic list
Make a generic view which will serve for every article.
var ArticleView = Backbone.View.extend({
tagName: 'p',
className: 'superDog',
render: function() {
// apply the template
this.$el.html(this.model.get('html'))
.show()
.animate({
top: this.model.get('top'),
left: this.model.get('left')
}, 3000);
return this; // always return this in render.
},
});
Then use this view inside a generic article list view.
var ArticleList = Backbone.View.extend({
render: function() {
this.$el.empty();
this.collection.each(this.renderArticle, this);
return this;
},
renderArticle: function(model) {
var view = new ArticleView({
model: model
});
this.$el.append(view.render().el);
},
});
And use Backbone models and a collection to convey the data.
var list = new ArticleList({
collection: new Backbone.Collection([{
id: '1A',
color: 'black',
top: '300',
left: '300',
html: 'hello world'
},
{
id: '1B',
color: 'blue',
top: '800',
left: '800',
html: 'Hello Everyone'
},
{
id: '1C',
color: 'blue',
top: '600',
left: '1000',
html: 'Hello No One'
}
])
});
list.render();

Related

Highchart: How to change y-axis title text inside angularjs controller?

I have created highchart directive
App.directive('hcChart', function ($parse) {
'use strict';
return {
restrict: 'E',
replace: true
,
template: '<div><div class="chart"></div></div></div>',
link: function (scope, element, attrs) {
attrs.chart = new Highcharts.chart(element[0], {
xAxis: {
title: {
text: "Date"
},
type: 'datetime'
// labels: {
// step: 24
// }
// ,
// tickInterval: 2
},
yAxis: {
title: {
text: "Value"
}
},
dataLabels: {
enabled: true
}
,
title: {
text: ""
},
chart: {
opacity: 0.51,
backgroundColor: "white",
// plotBackgroundColor: 'rgba(0, 0, 0, 0.7)',
plotBackgroundColor: 'white',
// width: 1600,
height: 800,
zoomType: 'x',
resetZoomButton: {
position: {
x: -140,
y: 0
}
}
},
tooltip: {
crosshairs: {
width: 3,
color: 'black',
dashStyle: 'shortdot'
}
how to change y-axis title text inside controller.
As i want to show different unit for different selection.
inside controller i'm using $scope.myseries for data and $scope.categories for x-axis date time.
html code
<hc-chart id="container" categories="{{myCategories}}" series="{{mySeries}}">Placeholder for generic chart </hc-chart>
how to use $scope to update y-axis?
i tried using
$scope.yAxis[0].setTitle({text : "abc"})
but its throwing errror. not defined property.
any help please!
To change yAxis title inside angularjs controller, we need to set its property:
Highcharts.charts[0].yAxis[0].setTitle({
text: $scope.NAME
});

AngularJs: How to use web worker with makepdf

There is a solution here that explains how to use web worker with makepdf. However, I want to know how to apply this solution to angular using requirejs.
I have tried to use ngwebworker along with requireJs, as the RequireJS within webworker, but I had no success. Can someone help me?
EDIT:
To make it easier to visualize the problem, I will put on this edit the code that it is not working:
$scope.exportToPDF = function(){
var list = $rootScope.orderedData;
var body = [];
var headers = new Array();
headers.push({ text: 'A', fillColor: '#0075E5', color: '#ffffff'});
headers.push({ text: 'B', fillColor:#0075E5', color: '#ffffff'});
headers.push({ text: 'C', fillColor:#0075E5', color: '#ffffff'});
headers.push({ text: 'D', fillColor:#0075E5', color: '#ffffff'});
headers.push({ text: 'E', fillColor:#0075E5', color: '#ffffff'});
headers.push({ text: 'F', fillColor:#0075E5', color: '#ffffff'});
body.push(headers);
for (var key in list)
{
if (list.hasOwnProperty(key)){
var position = list[key];
var fila = new Array();
fila.push( { text: position.a.toString(), fillColor: '#ffffff' } );
fila.push( { text: position.b.toString(), fillColor: '#ffffff'} );
fila.push( { text: position.c.toString(), fillColor: '#ffffff'} );
fila.push( { text: position.d.toString().substring(0,5) + "...", fillColor: '#ffffff'} );
fila.push( { text: position.e.toString(), fillColor: '#ffffff'} );
body.push(fila);
}
}
var dd = {
background: [{
width: 30,
alignment: 'left'
}],
pageOrientation: 'landscape',
footer: function(currentPage, pageCount) { return currentPage.toString() + '/' + pageCount;},
info: {
title: 'Title',
author: 'Me'
},
content: [
{ text: 'Text', style: 'header' },
{
style: 'tableHeader',
table:
{
dontBreakRows: true,
headerRows: 1,
widths: ['5%', '10%', '10%', 'auto', '15%', 'auto', 'auto', '10%', '10%', 'auto', '4%', '10%'],
body: body
}
}
],
styles: {
header: {
fontSize: 18,
bold: true,
margin: [0, 0, 0, 10],
alignment: 'center'
},
subheader: {
fontSize: 16,
bold: true,
margin: [0, 10, 0, 5]
},
tableExample: {
margin: [0, 5, 0, 15]
},
tableHeader: {
bold: true,
fontSize: 9,
color: 'black',
margin: [0, 5, 0, 15]
}
},
defaultStyle: {
},
};
var obj = pdfMake.createPdf(dd) // FAST PROCESS!
var myWorker = Webworker.create(downloadIt);
myWorker.run(obj).then(function(body) {
});
function downloadIt(obj) {
obj.download("Title.pdf"); // REALLY SLOW PROCESS THAT SHOULD BE IN BACKGROUND
}
}
The problem is that to transfer an object to a web worker, they suggest to use JSON.parse and JSON.stringify. However, if I use that on my object, I will loose the method "download". Is there a way to send this object to my function downloadIt without loosing the method download of pdfmake object?

Visualization: Pie Chart Legend Text color based on Value

I'm using ng-google-chart (Google Chart Api Directive Module for AngularJS version 0.0.11) with Google Pie charts and I'm trying to display Legend Text in the same color as slices color.
Pie Chart View
Is there any way to place slices colors into the legend.textStyle option?
Pie Chart Options
drvPie.options = {
pieHole: 0.9,
pieSliceText: 'value',
pieSliceTextStyle: {
'fontSize': '25'
},
slices: {
0: { color: 'green' },
1: { color: 'orange' },
2: { color: 'red' }
},
height: '100%',
chartArea: {'width': '100%', 'height': '70%'},
legend: {
"textStyle": {
color: 'blue',
fontSize: 15
},
labeledValueText: 'value',
"position": "labeled"
}
};
Unfortunately it is not supported to specify a separate legend style per item, but you could consider the following solution that demonstrates how to customize legend labels:
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task Status', 'Count'],
['At work', 22],
['Terminated', 3],
['Not working', 13]
]);
var options = {
pieHole: 0.9,
pieSliceText: 'value',
pieSliceTextStyle: {
'fontSize': '25'
},
slices: {
0: { color: 'green' },
1: { color: 'orange' },
2: { color: 'red' }
},
height: '100%',
chartArea: { 'width': '100%', 'height': '70%' },
legend: {
"textStyle": {
fontSize: 15
},
labeledValueText: 'value',
"position": "labeled"
}
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
google.visualization.events.addOneTimeListener(chart, 'ready', function(){
configureLegendLabel(data,options);
});
google.visualization.events.addListener(chart, 'onmouseover', function (e) {
configureLegendLabel(data,options);
});
google.visualization.events.addListener(chart, 'onmouseout', function (e) {
configureLegendLabel(data,options);
});
chart.draw(data, options);
}
function configureLegendLabel(data,options)
{
for(var key in options.slices){
var labelText = data.getValue(parseInt(key),0);
var label = $("text:contains('" + labelText + "')");
label.attr('fill',options.slices[key].color);
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script>
<div id="piechart" style="width: 900px; height: 500px;"></div>

Getting Error while loading data using angularjs and google charts

I am getting "All series on a given axis must be of the same data type" when loading the data.Please find the fiddle code in the below link
https://jsfiddle.net/smsh/9y5hrvne/
var app = angular.module('app', []);
app.directive('chart', function() {
return {
restrict: 'EA',
replace: true,
scope: {
data: '=data'
},
// template: '<div class="chart"></div>',
link: function(scope, element, attrs) {
var chart = new google.visualization.LineChart(element[0]);
var options = {
hAxis: {
gridlines: {
color: 'transparent'
},
format :"MMM dd",
textStyle:{
color: '#FFF',
fontName: 'Verdana',
fontSize: 11
},
showTextEvery:2
},
vAxis: {
gridlines:{
count:4,
color: '#FFF'
},
baselineColor:"#FFF",
format: '#\'%\'',
textStyle:{
color: '#FFF',
fontName: 'Verdana',
fontSize: 11
},
},
pointSize: 6,
pointShape: { type: 'circle' },
lineWidth:2,
legend: {
position: 'none'
},
backgroundColor: '#000000',
tooltip: {
textStyle: {
fontName: 'Calibri',
fontSize: 12
}
}
};
scope.$watch('data', function(v) {
var data = google.visualization.arrayToDataTable(v);
chart.draw(data, options);
});
}
};
});
app.controller('ChartController', function($scope) {
$scope.scoreHistory = [];
$scope.loadDataFromServer = function() {
var x = [
['interval', 'count','color']
];
var scoreHistory = [
{
intervalStart:new Date(2013, 5,1),
count:33,
color:'#ED1C24'
},
{
intervalStart:new Date(2013, 5,7),
count:50,
color: '#FFC90E'
},
{
intervalStart:new Date(2013, 5,8),
count:22,
color: '#ED1C24'
},
{
intervalStart:new Date(2013, 5,9),
count:45,
color: '#FFC90E'
},
{
intervalStart:new Date(2013, 5,13),
count:83,
color: '#ED1C24'
},
{
intervalStart:new Date(2013, 5,18),
count:80,
color: '#22B14C'
},
{
intervalStart:new Date(2013, 5,23),
count:100,
color: '#22B14C'
}
];
angular.forEach(scoreHistory, function(record, key) {
x.push([
record.intervalStart,
record.count,
record.color
]);
});
$scope.scoreHistory = x;
};
});
This controller i am using for getting the data and creating a angular directive to show the google line chart data in the UI.
you are getting "All series on a given axis must be of the same data type" because
$scope.scoreHistory = [["interval", "count", "color"], [Sat Jun 01 2013 00:00:00 GMT+0200 (CEST), 33, "#ED1C24"], ...]
your first element of array are your series, all strings and the rest of the elements is a data to display, don't think that the structure is right here, please check this link to have a look how this should be done.
I got the solution by doing the below code snippets:-
var x = [
['Date', 'Percentage', {'type': 'string', 'role': 'style'}]
];
var scoreHistory = [
{
intervalStart:new Date(2013, 5,1),
count:33,
color:'#ED1C24'
},

Render Two charts separate charts using angular js directives

I am trying to render two seperate charts using seperate directives for each charts, since the data is different ( also I am no expert in AngualrJs ). But only one chart was rendering to view. Please can someone help with what I have to do so that I can see both charts.Thanks.
'use strict';
angular.module('AngularApp',['AngularApp.directives']);
/*Controllers*/
var HighChartController = function HighChartController($scope) {
$scope.templateUrl = '/_layouts/AngularControls/TestController/View2.html';
$scope.type = '107';
$scope.initData = function () {
$scope.data = [
['Fire', 47.0],
['Wind', 33.0],
['Natural', 20.0]
];
}
$scope.loadChart = function () {
$scope.data1 = [60];
$scope.data2 = [40];
}
$scope.initData();
$scope.loadChart();
}
/* Directives */
angular.module('AngularApp.directives', []).
directive('drawPieChart', function () {
return function (scope, element, attrs) {
var container = $(element).attr("id");
scope.$watch('data', function () {
console.log('data');
drawPlot();
}, true);
var drawPlot = function () {
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: container,
margin: [0, 0, 0, 0],
spacingTop: 0,
spacingBottom: 0,
spacingLeft: 0,
spacingRight: 0
},
title: {
text: null
},
credits: {
enabled: false
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
size: '100%',
dataLabels: {
enabled: false
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: scope.data
}]
});
}
}
});
angular.module('AngularApp.directives', []).
directive('drawBarChart', function () {
return function (scope, element, attrs) {
var container = $(element).attr("id");
scope.$watch('data', function () {
drawPlot();
}, true);
var drawPlot = function () {
var chart = new Highcharts.Chart({
chart: {
type: 'column',
renderTo: container,
marginRight: 50,
events: {
}
},
title: {
text: 'Test Scores',
style: {
color: 'black',
fontWeight: '700',
fontFamily: 'Arial',
fontSize: 20
}
},
xAxis: {
categories: [],
title: {
text: null
},
gridLineWidth: 0,
minorGridLineWidth: 0,
labels: {
style: {
color: 'black',
fontWeight: '700',
fontFamily: 'Arial',
fontSize: 11,
width: 90
}
}
},
yAxis: {
min: 0,
max: 100,
gridLineWidth: 0,
minorGridLineWidth: 0,
labels: {
enabled: false
},
title: {
text: null
}
},
tooltip: {
valueSuffix: ' million'
},
plotOptions: {
series: {
stacking: 'percent'
},
bar: {
dataLabels: {
enabled: false
}
}
},
legend: {
enabled: false,
layout: 'vertical',
align: 'right',
verticalAlign: 'bottom',
x: -40,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: '#FFFFFF',
shadow: true
},
credits: {
enabled: false
},
series: [{
name: 'null',
data: scope.data2,
borderRadius: 0,
color: "gray"
}, {
name: 'Values',
data: scope.data1,
color: "green",
borderRadius: 0
}]
});
}
}
});
Here is the markup
<div id="barChartContainer" draw-bar-chart =""></div>
</div>
<div id="pieChartContainer" draw-pie-chart="">
</div>
As Oledje mentioned, you declared the AngularApp.directives twice, but there was also an issue with how you are actually referencing the data for the charts in the directive code. I would recommended that you create an isolated scope for each directive and map the properties for the chart data in the scope definition.
So instead of
.directive('drawPieChart', function () {
return function (scope, element, attrs) {
var container = $(element).attr("id");
scope.$watch('data', function () {
console.log('data');
drawPlot();
}, true);
var drawPlot = function () {...};
};
}
You should do
.directive('drawPieChart', function () {
return {
restrict: 'E',
scope: {
chartData: "="
},
link: function (scope, element, attrs) {
scope.$watch('chartData', function (newVal,oldVal) {
if (newVal) {
drawPlot();
}
}, true);
var drawPlot = function () {
// use scope.chartData for the data
};
}
};
}
And then you also need the corresponding HTML
<draw-pie-chart chart-data="pieChartData">
And in your Controller do $scope.pieChartData=[];
Here is a jsFiddle with all of my changes: http://jsfiddle.net/callado4/9far5/5/ (look at the history to see how I progressed)
I think that your problem is that you declare a module twice.
try write not
angular.module('AngularApp.directives', []).
directive('drawPieChart'...)
angular.module('AngularApp.directives', []).
directive('drawBarChart'...)
but
angular.module('AngularApp.directives', []).
directive('drawPieChart'...).
directive('drawBarChart'...)
or
var app = angular.module('AngularApp.directives', []);
app.controller('Ctrl', ...)
app.directive('drawPieChart'...);
app.directive('drawBarChart'...);
Examples:
http://jsfiddle.net/GDQ6B/2/
http://jsfiddle.net/EYz9U/1/

Resources