i'm a angularjs new bee.What i'm trying to accomplish is display a image using template of angularjs directive and on click on image i want a marker to be placed on the image.Dont know y its not working.
My first angular js directive
directive('hello',function(){
return{
template:
'<img id="map" src="http://www.lonelyplanet.com/maps/asia/india/map_of_india.jpg" />',
link: function(scope,element,attrs){
$('#map').click(function(e){
$('#marker').css('left', e.pageX).css('top', e.pageY).show();
});
},
};
})
Here is the html code
<hello>
<img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" />
</hello>
You are missing the restrict : 'E' option, by default restrict has the value AC which is attribute and class, in your case you are using the directive as an element.
Update: Based on comment
angular.module('test', []).directive('hello', function() {
return {
restrict : 'E',
template : '<div style="position: relative"><img id="map" src="http://www.lonelyplanet.com/maps/asia/india/map_of_india.jpg" /><img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" /></div>',
replace: true,
link : function(scope, element, attrs) {
$('#map').click(function(e) {
$('#marker').css('left', e.pageX).css('top', e.pageY)
.show();
});
}
};
});
Demo: Fiddle
Some other possible issues:
widgetForm and restrict is 'E' or 'A', you should use <widget-form/> , not <widgetForm/>.By default when you make a directive in angularjs. if you ignore restrict property angularjs assume it as an attribute. as your html showing you should write your returning object as bellow
<body ng-app="myApp">
<hello>
<div id="marker"></div>
</hello>
</body>
and in angular the element is already a jQuery object even if you do not add jquery it will use its own implementation call jQLite. so you should only use
var app = angular.module('myApp', []);
app.directive('hello',function(){
var linkFn = function (scope,element,attrs){
element.bind('click',function(e){
$('#marker').css('left', e.pageX).css('top', e.pageY).show();
});
};
return {
restrict : "E",
link: linkFn,
transclude:true,
template:'<div ng-transclude><img id="map" src="http://www.lonelyplanet.com/maps/asia/india/map_of_india.jpg" /></div>'
};
});
i hope it helps working exmaple
What @Arun said is correct. But it is not mandatory. By default ur directive will be attribute.
So Instead of using ur directive as a element
<hello>
<img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png"style="display: none; position: absolute;" />
</hello>
try it as an attribute, like this
<img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" hello />