agasthyan agasthyan - 5 months ago 5
Javascript Question

Angular directive not working

I am an AngularJS newby. I am trying to display an image using a template of an AngularJS directive and on click of the image I want a marker to be placed on the image. I Don't know why it is not working.

The first 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();
}
);
},
};
});


The html code

<hello>
<img id="marker" src="http://maps.google.com/mapfiles/ms/micons/blue.png" style="display: none; position: absolute;" />
</hello>

Answer

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