multiple markers on same location google maps, so OverlappingMarker - angularjs

{literal}
<script type="text/javascript">
function TypeaheadCtrl($scope, $http, $compile) {
var firstLoad = true;
var markerClusterer = null;
var oms = null;
$scope.myMarkers = [];
$scope.infoWindow = new google.maps.InfoWindow();
$scope.mapOptions = {
center: new google.maps.LatLng(41.222298, -73.439740),
zoom: 8,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
$scope.getDynamicMin = function(){ $scope.dynamic_min; }
$scope.getDynamicMax = function(){ $scope.dynamic_min; }
$scope.dynamic_value = ($scope.dynamic_max - $scope.dynamic_min)/2;
$scope.SliderCtrlFn = function(vrange) {
$scope.min = (vrange >= 1 && vrange <=3) ? 1 : (vrange >=4 && vrange <=15) ? 18 : (vrange >= 16 && vrange <=25) ? 25 : (vrange >= 26 && vrange <=36) ? 36 : (vrange >= 37 && vrange <=51) ? 45 : 60;
$scope.max = (vrange >= 1 && vrange <=3) ? 130 : (vrange >=4 && vrange <=15) ? 24 : (vrange >= 16 && vrange <=25) ? 35 : (vrange >= 26 && vrange <=36) ? 44 :(vrange >= 37 && vrange <=51) ? 59: 130;
$scope.getcontacts('Age');
}
$scope.Gender_selectAction = function () {
$scope.getcontacts('Gender');
}
$scope.genders = [{value: '1',name: 'Female'}, {value: '2',name: 'Male'}];
$scope.getcontacts = function (fieldname) {
CDname = $scope.cong_dist;
SDname = $scope.senate_dist;
Assembly = $scope.assembly_dist;
Pname = $scope.precinct_name;
Citycode = $scope.city_code;
Gender = $scope.Gender;
Minage = $scope.min;
Maxage = $scope.max;
var dataUrl = {/literal}"{crmURL p='civicrm/contact/mapcontacts/filter/getcontacts' }"{literal};
return $http.get(dataUrl, {
params: {
fieldName:fieldname,
CDname:CDname,
SDname:SDname,
Assembly:Assembly,
Pname:Pname,
Citycode:Citycode,
Gender:Gender,
Minage:Minage,
Maxage:Maxage,
sensor: false
}
}).then(function(res){
$scope.myMarkers = [];
if(res.data && res.data != "null" && res.data != ""){
var infoWindow=$scope.infoWindow;
angular.forEach(res.data, function(item){
marker = $scope.createmarker(item,infoWindow);
var oms = new OverlappingMarkerSpiderfier($scope.nggMap);
$scope.myMarkers.push(marker);
});
$scope.infoWindow.close();
var markerCluster = new MarkerClusterer($scope.nggMap, $scope.myMarkers);
}
return $scope;
});
}
$scope.createmarker = function(item,infoWindow){
var point = new google.maps.LatLng(item.geo_code_1,item.geo_code_2);
var marker = new google.maps.Marker({
map: $scope.nggMap,
position: point,
contactid: item.contact_id,
title: item.display_name ,
zIndex: google.maps.Marker.MAX_ZINDEX + 5
}); //,animation: google.maps.Animation.DROP
marker.content = '<div class="infoWindowContent">' + item.display_name + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h2>' + marker.content + '</h2>');
infoWindow.open($scope.nggMap, marker);
});
oms.addMarker(marker);
return marker;
}
ms.addListener('click', function(marker, event) {
$scope.infoWindow.open($scope.nggMap, marker);
});
}
</script>
{/literal}
so i want to use OverlappingMarkerSpiderfier anybody can plz help me how to use it??
i have already used library in my html.
and put OverlappingMarkerSpiderfier code i am getting error so plz can anybody help me to solve this issue.

Try to Use Like
for (var i = 0; i < window.mapData.length; i ++) {
var datum = window.mapData[i];
var loc = new gm.LatLng(datum.lat, datum.lon);
var marker = new gm.Marker({
position: loc,
title: datum.h,
map: map
});
marker.desc = datum.d;
oms.addMarker(marker); // <-- here
}
You will find the details doc. and code regarding this refer this link

Related

Using FusionCharts with Ext JS

I am thinking about using FusionCharts in an application entirely build with Ext JS so far.
However, I don't believe there's a specific recommended implementation or connector to easily add FusionCharts to an Ext JS app. There are various examples online of others adding the charts within an Ext JS app though:
http://jsfiddle.net/fusioncharts/xujmxjcb/
http://jsfiddle.net/fusioncharts/5j8s7g68/
https://www.sencha.com/forum/showthread.php?218834-How-to-integrate-fusion-charts-with-Extjs4&p=830921&viewfull=1#post830921
The last one discusses a way to create an Ext JS class for FusionCharts that "wraps" some of the charting functionality within a proper class:
/* * ?????? : var testdata = { part : { 'Jul 01' : 2000, 'Aug 02' : 2400, 'Sep 03' : 2000, 'Oct 04' :
* "", 'Dec 05' : null }, zoo : { 'Jul 01' : 4000, 'Aug 02' : 3400, // 'Sep 03' : 3000, // 'Oct 04' :
* 5200, 'Dec 05' : 4210 }, hotel : { // 'Jul 01' : 6000, 'Aug 02' : 6400, // 'Sep 03' : 7000, 'Oct
* 04' : 8200, 'Dec 05' : 8100 } }; // this.setChartData(testdata); ????????????
*/
/**
* ????
* #class Ext.ux.MSLineChart
* #extends Ext.Panel
* #cgf initData : Object ??????.
* #cgf DwrAction : DWR???? ??????.
* #cgf baseLoadParam : Object DWR???????.
* #cgf autoShowChart : boolean ??(true) ??????????.
* #function loadData() : ??DWR????,????.
* #cgf imageType ???? : MSColumn2D,MSColumn3D,MSLine,MSArea,MSBar2D,MSBar3D StackedColumn2D,
* StackedColumn3D,StackedArea2D,StackedBar2D,StackedBar2D,StackedBar3D
*/
Ext.ux.FusionChart = Ext.extend(Ext.Panel, {
width : 1000,
height : 600,
border : false,
layout : 'fit',
autoShowChart : true,
animationflex : true,
imageType : 'MSLine',
constructor : function(config) {
Ext.apply(this, config);
this.isLineChart = true; // ??????????
var chartDom = Ext.core.DomHelper.append(document.body, {
id : 'ux-fc-' + ++Ext.AbstractComponent.AUTO_ID,
tag : 'div',
cls : 'x-hidden',
style : 'z-index:-1;width:100%;height:100%'
});
this.chart = new FusionCharts(WEBPATH + '/common/fc/' + this.imageType + '.swf', chartDom.id, '100%', "100%", "0",
"1", null);
this.chart.addParam("wmode", "transparent");// ???,????EXT
if (this.initData) {
this.setChartData(this.initData);
} else if (this.DwrAction && this.autoShowChart === true) {
this.loadData(this.baseLoadParam);
}
this.contentEl = this.chart.getAttribute('id');
Ext.ux.FusionChart.superclass.constructor.call(this);
this.on('render', this.renderPanel, this);
},
renderPanel : function() {
},
/** ??DWR??????. */
loadData : function(param) {
param = param || {};
Ext.applyIf(param, this.baseLoadParam);
var setChartData = Ext.bind(this.setChartData, this);
this.DwrAction(param, setChartData);
},
// ??????XML???render chart
setChartData : function(data) {
var animation = this.animationflex == true ? 1 : 0;
var DataXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<chart animation =\"" + animation
+ "\" baseFont=\"??\" baseFontSize=\"12\">";
var valuePartXML = "", trendlinesXML = "";
var xNameArray = [];
if (data['trendlines']) { // ???(??:??,???), ????? : {?:??}
trendlinesXML = "<trendlines> ";
for (var key in data['trendlines']) {
trendlinesXML += "<line startValue='" + key + "' color='" + data['trendlines'][key].replace('#', '')
+ "' displayValue='" + key + "' showOnTop='1' />";
}
trendlinesXML += "</trendlines>";
delete data['trendlines'];
}
DataXML += "<categories>"
for (var key in data) {
if (key.length > 0) {
var record = data[key];
for (var xName in record) {
/* xNameArray.indexOf(xName) == -1 && */
if (xName && String(xName).length > 0) {
DataXML += "<category label=\"" + xName + "\"/>"; // x???
xNameArray.push(xName);
}
}
break; // ????, ???????????. (???????)
}
}
DataXML += "</categories>";
for (var key in data) { // ??
if (key.length > 0) {
var record = data[key];
valuePartXML += "<dataset seriesName=\"" + key + "\">";
for (var i = 0; i < xNameArray.length; i++) {
var xName = xNameArray[i];
if (record[xName] && String(record[xName]).length > 0) {
valuePartXML += "<set value=\"" + record[xName] + "\"/>"; // x???
} else if (this.isLineChart == true) {
record[xName] = this.getEstimated(xName, record, xNameArray);
valuePartXML += "<set showValue =\"0\" toolText=\" \" displayValue=\" \" value=\"" + record[xName] + "\"/>"; // x???
}
}
valuePartXML += "</dataset>";
}
}
DataXML += valuePartXML + trendlinesXML;
DataXML += "</chart>"
this.chart.setDataXML(DataXML);
this.chart.show(); // render
},
/** line????????,?????. */
getEstimated : function(xName, record, xNameArray) {
var front = null;
var back = null;
var space = 2;
for (var i = xNameArray.indexOf(xName) - 1; i > -1; i--) {
var currUp = record[xNameArray[i]];
if (currUp != null && String(currUp).length > 0) {
front = Number(currUp);
break;
}
space++;
}
for (var i = xNameArray.indexOf(xName) + 1; i < xNameArray.length; i++) {
var currDown = record[xNameArray[i]];
if (currDown != null && String(currDown).length > 0) {
back = Number(currDown);
break;
}
space++;
}
if (front == null || back == null) {
return null;
} else {
return (back - front) / space + front;
}
}
})
What is the best way to proceed and what are the advantages/disadvantages?
Any help is greatly appreciated and sorry for the rookie question!
Best
/R

Load from JSON with dynamic patterns, patternSourceCanvas is not defined error return by the serialize JSON data

I am trying to save Fabric.js canvas and reload it using loadFromJson. But I am getting error patternSourceCanvas is not defined. I thought I should make it global so I removed var.
How to set the global variable in Fabric JS and use var patternSourceCanvas?
When I use the code below, then everything is working fine and the JSON is loaded easily.
var t = https://image.freepik.com/free-photo/roof-texture_21206171.jpg
fabric.util.loadImage(t, function(t) {
var svg_width = i.width;
console.log('svg widh' + i.width + 'svg height' + i.height);
console.log('img width t'+ t.width + ' img height' + t.height);
if(svg_width >= 300){
if (i.isSameColor && i.isSameColor() || !i.paths) {
i.setPatternFill({
source: t, repeat: 'repeat', offsetX:200 , offsetY : -110 // working
}), e.fabric.renderAll();
console.log('in if image 300 up ', t);
} else if (i.paths){
for (var r = 0; r < i.paths.length; r++)
i.paths[r].setPatternFill({
source: t, repeat: 'repeat' , offsetX: -100 , offsetY:-110
}), e.fabric.renderAll();
console.log('in image elseeee 300 up ', t);
}
}
})
But when I fill some other new shape with the new patternSourceCanvas variable then it's not working. Kindly help me with dynamic patterns.
var t = https://image.freepik.com/free-photo/roof-texture_21206171.jpg
fabric.Image.fromURL(t, function (img) {
img.scaleToHeight(200);
var patternSourceCanvas = new fabric.StaticCanvas();
patternSourceCanvas.add(img);
patternSourceCanvas.renderAll();
var pattern = new fabric.Pattern({
source: function() {
patternSourceCanvas.setDimensions({
width: img.getScaledWidth() ,
height: img.getScaledHeight()
});
patternSourceCanvas.renderAll();
return patternSourceCanvas.getElement();
},
repeat: r
});
console.log('pattern', pattern);
//p.set('fill', pattern);
canvas.renderAll();
if (i.isSameColor && i.isSameColor() || !i.paths) {
i.setPatternFill(pattern);
} else if(i.paths) {
for (var r = 0; r < i.paths.length; r++) {
i.paths[r].setPatternFill(pattern);
}
}
e.fabric.renderAll();
});
You need to put patternSourceCanvas to global scope/ scope where loadFromJSON can access patternSourceCanvas. Else you can use cors enabled image directly.
DEMO
var imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/2/22/Wikimapia_logotype.svg';
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
width: 200,
height: 200,
strokeWidth: 2,
stroke: '#000'
})
canvas.add(rect);
fabric.Image.fromURL(imageUrl, function(img) {
img.scaleToHeight(200);
var patternSourceCanvas = new fabric.StaticCanvas();
patternSourceCanvas.add(img);
patternSourceCanvas.setDimensions({
width: img.getScaledWidth(),
height: img.getScaledHeight()
});
patternSourceCanvas.renderAll();
var pattern = new fabric.Pattern({
source: patternSourceCanvas.getElement()
},
function(patternObj) {
rect.fill = patternObj;
rect.dirty = true;
canvas.renderAll();
});
}, {
crossOrigin: 'annonymous'
});
function loadfromjson() {
var json = canvas.toJSON();
canvas.clear();
setTimeout(function() {
canvas.loadFromJSON(json, canvas.renderAll.bind(canvas));
}, 1000)
}
canvas{
border:2px solid #000;
}
<canvas id="canvas" width="300" height="300"></canvas><br>
<button onclick="loadfromjson()">loadfromjson </button>
<script src='https://rawgit.com/kangax/fabric.js/master/dist/fabric.js'></script>

Mapbox & Angular Iframe doens't work on Firefox

I have deployed Angular to my Codigniter project and also I have deployed MapBox Leaflet to it as part of my project, but it doesn't work on Firefox, what I have done I used the scope and angular object inside the iFrame I use to load the mapbox map view. It works seamlessly on other browsers, but it doesn't work on Firefox.
This is the error I get on my Console
WARNING: Tried to load angular more than once.
angular.min.js (line 206)
TypeError: a is null
<iframe width="100%" height="600px" src="URL/ADDRESS/TO/MAP/WHERE/I/REUSE/ANGULAR/AND/SCOPE/AGAIN" frameborder="0"></iframe>
<!DOCTYPE html>
https://api.mapbox.com/mapbox.js/v2.2.4/mapbox.js'>
https://api.mapbox.com/mapbox.js/v2.2.4/mapbox.css' rel='stylesheet' />
" type="text/javascript">
https://api.mapbox.com/mapbox.js/plugins/mapbox-directions.js/v0.4.0/mapbox.directions.css' type='text/css' />
" />
</head>
<body class="plugin-mapbox-driving-direction-mapview">
<section class="">
<div class="">
<div id='map'></div>
<div id='inputs'></div>
<div id='errors'></div>
<div id='directions'><div id='routes'></div><div id='instructions'></div></div>
<script>
var angular = window.parent.angular,
scope = window.parent.angular.element(window.frameElement).scope(),
initialization = true;
//console.log("angular", angular, "angular");
//console.log("scope", scope, "scope");
var startCoordinates = scope.__route[0],
endCoordinates = scope.__route[1];
var startLocation = {
lat: angular.isDefined(startCoordinates.lat) ? startCoordinates.lat : null,
lng: angular.isDefined(startCoordinates.lng) ? startCoordinates.lng : null,
loc: scope.pinOriginLocation
},
endLocation = {
lat: angular.isDefined(endCoordinates.lat) ? endCoordinates.lat : null,
lng: angular.isDefined(endCoordinates.lng) ? endCoordinates.lng : null,
loc: scope.pinDestinationLocation
},
origin = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [startLocation.lng, startLocation.lat]
},
properties: {
name: startLocation.loc
}
},
destination = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [endLocation.lng, endLocation.lat]
},
properties: {
name: endLocation.loc
}
};
L.mapbox.accessToken = "<?php echo $this->config->item('mapbox_api_accesstoken'); ?>";
var __journey = scope.__journey;
var map = L.mapbox.map('map', 'mapbox.streets', {zoomControl: false});
map.attributionControl.setPosition('bottomleft');
var directions = L.mapbox.directions();
var directionsLayer = L.mapbox.directions.layer(directions).addTo(map);
var directionsRoutesControl = L.mapbox.directions.routesControl('routes', directions).addTo(map);
var directionsInputControl = L.mapbox.directions.inputControl('inputs', directions).addTo(map);
var directionsErrorsControl = L.mapbox.directions.errorsControl('errors', directions).addTo(map);
var directionsInstructionsControl = L.mapbox.directions.instructionsControl('instructions', directions).addTo(map);
var wayPoints = [];
if(angular.isDefined(scope.__journey.__route) && scope.__journey.__route.length > 2) {
for(var i in scope.__journey.__route) {
if(scope.__journey.__route.length <= 20 || (wayPoints.length <= 20 && Number(i)%(Math.round(scope.__journey.__route.length / 20)) == 0))
wayPoints.push(L.latLng(scope.__journey.__route[i].latitude,scope.__journey.__route[i].longitude));
}
}
console.log("wayPoints", wayPoints, "wayPoints");
setQuery(startLocation, true, origin, endLocation, true, destination, wayPoints);
//directions.setOrigin(origin, true).setDestination(destination, true).query(undefined, false);
scope.$watch("pinOriginLocation", function(newval, oldval) {
if(angular.isDefined(newval) && newval.length >= 20 && newval !== oldval) {
startCoordinates = scope.getCordinates(newval);
startLocation = {
lat: angular.isDefined(startCoordinates.lat) ? startCoordinates.lat : null,
lng: angular.isDefined(startCoordinates.lng) ? startCoordinates.lng : null,
loc: scope.pinOriginLocation
};
origin = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [startLocation.lng, startLocation.lat]
},
properties: {
name: startLocation.loc
}
};
initialization = false;
setQuery(startLocation, undefined, origin, endLocation, undefined, destination, wayPoints);
//directions.setOrigin(origin).setDestination(destination).query(undefined, false);
}
});
scope.$watch("pinDestinationLocation", function(newval, oldval) {
if(angular.isDefined(newval) && newval.length >= 20 && newval !== oldval) {
endCoordinates = scope.getCordinates(newval);
endLocation = {
lat: angular.isDefined(endCoordinates.lat) ? endCoordinates.lat : null,
lng: angular.isDefined(endCoordinates.lng) ? endCoordinates.lng : null,
loc: scope.pinDestinationLocation
};
destination = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [endLocation.lng, endLocation.lat]
},
properties: {
name: endLocation.loc
}
};
initialization = false;
setQuery(startLocation, undefined, origin, endLocation, undefined, destination, wayPoints);
//directions.setOrigin(origin).setDestination(destination).query(undefined, false);
}
});
function suggestLocation(event, element) {
var el = $(element);
if(el.val().length >= 8 && event.keyCode == 32) {
$.ajax({
type : "POST",
url : siteVars.ajaxUrl+"webservice/lookupAddress",
datatype : "html",
data : {
"code" : siteVars.csrfHash,
"address" : el.val()
},
success: function(data) {
lookup = [];
if(!angular.equals(data, "")) {
data = JSON.parse(data);
for(var i in data) {
if(typeof data[i].location != 'undefined')
lookup.push(data[i].location);
}
displaySuggestion(el, lookup);
}
}
});
}
};
function displaySuggestion(element, lookup) {
var attr = element.attr("id") + "DataList";
var html = "";
$("#"+attr).remove();
if(lookup.length > 0) {
for(var i in lookup)
html += "<div onclick='selectSuggestion(\""+element.attr("id")+"\", \""+lookup[i]+"\")' class='autocomplete-suggestion' data-index='"+i+"'>"+lookup[i]+"</div>";
html = "<div class='autocomplete-suggestions' id='"+attr+"'>"+html+"</div>";
$(html).insertAfter(element);
}
};
function selectSuggestion(element, suggestion) {
var el = $("#"+element);
el.val(suggestion);
$("#"+el.attr("id")+"DataList").remove();
if(el.attr("id") == "mapbox-directions-origin-input")
directions.setOrigin(suggestion);
if(el.attr("id") == "mapbox-directions-destination-input")
directions.setDestination(suggestion);
if(directions.queryable()) {
initialization = false;
directions.query({proximity: map.getCenter()}, false);
}
}
function setQuery(startLocation, startLocationStatus, origin, endLocation, endLocationStatus, destination, wayPoints) {
if(!angular.isDefined(startLocation.loc) || angular.equals(startLocation.loc, "") || angular.equals(startLocation.loc, null))
directions.setOrigin(L.latLng(startLocation.lat, startLocation.lng), true);
else
directions.setOrigin(origin, true);
if(!angular.isDefined(endLocation.loc) || angular.equals(endLocation.loc, "") || angular.equals(endLocation.loc, null))
directions.setDestination(L.latLng(endLocation.lat, endLocation.lng), true);
else
directions.setDestination(destination, true);
if(angular.isDefined(wayPoints) && wayPoints.length > 0)
directions.setWaypoints(wayPoints);
//L.Routing.control({waypoints:wayPoints}).addTo(map);
console.log("wayPoints", wayPoints, "wayPoints");
return directions.query(undefined, false);
}
</script>
</div>
<?=$this->load->view("subviews/libraries_link")?>
</section>
</body>

Trying to create D3 + AngularJS Bar Chart

I would like to create a D3 Bar chart with angularjs. This is my directive, and currently I am having a couple of problems.
The chart is not appended to the directives div, but to html tag
Chart is appended multiple times, even though when watch is called, we only log one append
When loggin d3.select(jqElm[0]), it outputs the directives element
What am I doing wrong?
(function (angular, d3) {
'use strict';
var isDef = angular.isDefined,
aExtend = angular.extend,
aCopy = angular.copy,
isArray = angular.isArray,
isObject = angular.isObject,
aElement = angular.element,
isEqual = angular.equals;
angular.module('Widgets.Module')
.factory('ConstructorD3Bar', Constructor)
.directive('tmD3Bar', Directive);
Constructor.$inject = [
'Common'
];
Directive.$inject = [
'Common',
'ConstructorD3Bar'
];
function Constructor(Common) {
var cgenerator = Common.Generator;
function D3Bar(attrs) {
this._setProps(attrs);
}
D3Bar.prototype = {
_setProps: function (p) {
p = p || {};
this.id = isDef(p.id) ? p.id : cgenerator.id;
this.theme = isDef(p.theme) ? p.theme : 'D3Bar';
this.message = isDef(p.message) ? p.message : 'D3Bar';
this.data = isDef(p.data) ? p.data : [];
this.format = isDef(p.format) ? p.format : null;
this.tsv = isDef(p.tsv) ? p.tsv : null;
this.csv = isDef(p.csv) ? p.csv : null;
this.margin = isDef(p.margin) ? p.margin : { top: 0, bottom: 0, left: 0, right: 0};
this.boxWidth = isDef(p.boxWidth) ? p.boxWidth : Common.$window.innerWidth;
this.boxHeight = isDef(p.boxHeight) ? p.boxHeight : Common.$window.innerHeight;
this.width = isDef(p.width) ? p.width : Common.$window.innerWidth;
this.height = isDef(p.height) ? p.height : Common.$window.innerHeight;
this.init();
},
init: function () {
var that = this;
if (that.tsv !== null) {
d3.tsv(that.tsv, function (err, data) {
if (isDef(err) && err && err.status) {
switch (err.status) {
case 404:
return;
}
}
that.data = data;
});
}
},
toString: function () {
return this;
}
};
return {
create: function (props) {
return new D3Bar(props);
}
};
}
function Directive(
Common,
ConstructorD3Bar
) {
var directive = {
templateUrl: 'widgets/d3-charts/bar/bar.tpl.html',
controller: ctrl,
compile: compile,
scope: {
attrs: '=?'
},
replace: true,
restrict: 'AC'
};
return directive;
function compile(tElement, tAttrs) {
return {
pre: function (scope, jqElm, attr) {
scope.initWidget = function () {
if (!isDef(scope.attrs) || scope.attrs === null) {
scope.attrs = ConstructorD3Bar.create({});
}
var margin = scope.attrs.margin,
width = scope.attrs.boxWidth - margin.left - margin.right,
height = scope.attrs.boxHeight - margin.top - margin.bottom;
scope.attrs.width = width;
scope.attrs.height = height;
var formatPercent = d3.format('.0%');
scope.attrs.x = d3.scale
.ordinal()
.rangeRoundBands([0, width], 0.1, 1);
scope.attrs.y = d3.scale
.linear()
.range([height, 0]);
scope.attrs.xAxis = d3.svg
.axis()
.scale(scope.attrs.x)
.orient('bottom');
scope.attrs.yAxis = d3.svg
.axis()
.scale(scope.attrs.y)
.orient('left')
.tickFormat(formatPercent);
};
},
post: function (scope, jqElm, attr) {
scope.$on('$destroy', function () { });
scope.$watch(
function () {
return scope.attrs.data;
},
function (nValue, oValue) {
if (!nValue) {
return;
}
if (nValue.length === 0) {
return;
}
var data = nValue;
scope.attrs.svg = d3.select(jqElm[0])
.data(data)
.enter()
.append('svg')
.attr('width', scope.attrs.width + scope.attrs.margin.left + scope.attrs.margin.right)
.attr('height', scope.attrs.height + scope.attrs.margin.top + scope.attrs.margin.bottom)
.append('g')
.attr('transform', 'translate(' + scope.attrs.margin.left + ',' + scope.attrs.margin.top + ')');
data.forEach(function (d) {
d.frequency = +d.frequency;
});
scope.attrs.x.domain(data.map(function (d) {
return d.letter;
}));
scope.attrs.y.domain([0, d3.max(data, function (d) {
return d.frequency;
})]);
scope.attrs.svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + scope.attrs.height + ')')
.call(scope.attrs.xAxis);
scope.attrs.svg.append('g')
.attr('class', 'y axis')
.call(scope.attrs.yAxis)
.append('text')
.attr('transform', 'rotate(-90)')
.attr('y', 6)
.attr('dy', '.71em')
.style('text-anchor', 'end')
.text('Frequency');
scope.attrs.svg.selectAll('.bar')
.data(data)
.enter().append('rect')
.attr('class', 'bar')
.attr('x', function (d) {
return scope.attrs.x(d.letter);
})
.attr('width', scope.attrs.x.rangeBand())
.attr('y', function (d) {
return scope.attrs.y(d.frequency);
})
.attr('height', function (d) {
return scope.attrs.height - scope.attrs.y(d.frequency);
});
}
);
}
};
}
function ctrl($scope, $element, $attrs) {
var vm = $scope;
if (!isDef(vm.attrs) || vm.attrs === null) {
vm.attrs = ConstructorD3Bar.create({ });
}
var attrs = vm.attrs;
}
}
})(window.angular, window.d3);
<div id="{{ attrs.id }}" class="D3Bar" ng-class="attrs.theme" ng-init="initWidget()">
</div>
Remove .data().enter in .select
scope.attrs.svg = d3.select(jqElm[0])
.append('svg')
.attr('width', scope.attrs.width + scope.attrs.margin.left + scope.attrs.margin.right)
.attr('height', scope.attrs.height + scope.attrs.margin.top + scope.attrs.margin.bottom)
.append('g')
.attr('transform', 'translate(' + scope.attrs.margin.left + ',' + scope.attrs.margin.top + ')');

directive function calling multiple times in angularjs

I have created directive in anguular js to resize image in angularjs.
Here is the code of directive :
app.directive('resize1', function ($window) {
return {
restrict: 'A',
replace: true,
scope: {
params: '&',
path: '=',
siteurl: '='
},
link: function($scope, element, attrs) {
$scope.resizeImage = function() {
var size = 0;
var width = angular.element($window).width();
src = $(element).attr('src');
if (src != null || src != '') {
var url = parse_url(src).query;
var path = parse_url(src).path;
var str = url.split('&');
var link = '?';
$.each(str, function(index, value) {
pair = value.split('=');
if (pair[0] != 'h' && pair[0] != 'w') {
link = link + value + '&';
}
});
if (width >= 960) {
size = $scope.$eval($scope.params).gt960;
newWidth = size.w;
newHeight = size.h;
} else if (width < 960 && width >= 480) {
size = $scope.$eval($scope.params).bt480960;
newWidth = size.w;
newHeight = size.h;
} else {
size = $scope.$eval($scope.params).lt480;
newWidth = size.w;
newHeight = size.h;
}
link = link + 'h=' + newHeight + '&w=' + newWidth;
$(element).attr('src', path + link);
$(element).attr('ng-src', path + link);
$(element).closest('div.spinner').css({
'height' : newHeight,
'width' : newWidth,
'margin' : '0px auto'
});
}
};
angular.element($window).bind('resize', function() {
$scope.resizeImage();
});
$scope.$watch('path', function (){
//alert('df');
$scope.resizeImage();
});
}
}
});
and my html is :
<div class="list-view" ng-hide="productDetail == null">
<div class="list-view-img">
<div class="spinner">
<img resize1
ng-src="{{siteurl}}thumbnails/index?file={{path}}&h=200&w=200"
params="{lt480: {h: 300,w: 300}, bt480960: {h: 450,w: 450}, gt960: {h: 940,w: 940}}"
path="paths.products.primary_image + productDetail.primary_image"
siteurl="siteUrl"
/>
</div>
</div>
</div>
Now the problem is its working fine but directive function is called 3 times..
Can anybody tell me what can be wrong ? why it is called thrice though i have called it once ?

Resources