I am trying to create a AngularJS widget (with AngularJS custom directive) through which user will able to use the widget as branch-locator on google map. Eg:
<branch-locator id="someId" branch-info="JSON-ARRAY"></branch-locator>
Where the JSON array will be like:
[
{
city : 'Los Angeles',
desc : 'This city is amazing.',
lat : 34.0500,
long : -118.2500
},
{
city : 'Chicago',
desc : 'This is the second best city in the world!',
lat : 41.8819,
long : -87.6278
}
]
But I want this data not to be hard-coded, rather I want to pass this data dynamically through jQuery. My Intention is that the end user must not care about internal semantics of AngularJS; The only requirement to use this widget is availability of data.
Now, my problem is that passing data to the directive, results in string like:
[Object object, Object object]
Which is only string-array whose 0th index element is '[' not as expected:-
{
city : 'Los Angeles',
desc : 'This city is amazing..',
lat : 34.0500,
long : -118.2500
}
Following is the code snippet:
branchLocatorWidget.html
<script>
$(function(){
var cities = [
{
city : 'Toronto',
desc : 'This is the best city in the world!',
address : '',
lat : 43.7000,
long : -79.4000,
},
{
city : 'New York',
desc : 'This city is aiiiiite!',
address : '',
lat : 40.6700,
long : -73.9400
},
{
city : 'Chicago',
desc : 'This is the second best city in the world!',
address : '',
lat : 41.8819,
long : -87.6278
},
{
city : 'Los Angeles',
desc : 'This city is live!',
address : '',
lat : 34.0500,
long : -118.2500
},
{
city : 'Las Vegas',
desc : 'Sin City...\'nuff said!',
address : '',
lat : 36.0800,
long : -115.1522
}
];
$("branch-locator#someId").attr("branch-info",cities);
});
</script>
<div>
<branch-locator id="someId" branch-info=""></branch-locator>
</div>
BranchLocatorDirective.js
var uniqueId = 1;
var modified_id = "mapId";
define(["app"], function(app) {
var modulename = 'branchLocator';
angular.module("branchLocator", []).directive('branchLocator', function() {
return {
restrict: 'E',
replace: true,
scope: {
branchInfo : "@",
id : "@"
},
link: linkFunction,
templateUrl: 'js/widget/directives/branchLocator/template/' + modulename + 'Template.html',
};
});
var linkFunction = function(scope, element, attrs){
var cities = eval(scope.branchInfo);
console.log("From Directive: "+cities);
console.log("Array Property: "+cities[0].city);
console.log("Array Length: "+cities.length);
scope.uniqueId = '_'+uniqueId++;
modified_id = modified_id + scope.uniqueId;
modified_id = element.find('div').attr('id' , modified_id).attr("id");
plotMap(modified_id, cities, scope);
}
var plotMap = function(modified_id, cities, scope){
// logic to plot locations on the google map
}
});
branchLocatorTemplate.html
<div>
<div id="mapId{{::uniqueId}}"></div>
</div>
However, if I try to pass the same literal through the controller on the scope property, it works fine, but my requirement is to refrain the directive from any dependency.