Reputation: 363
I have a directive that only fires once and only when you start on the page with the directive.
What am I doing wrong?
HTML -
<div class="body">
<a href="#/systems"><div class="viewBySys"></div></a>
<div ng-view class="container reveal-animation"></div>
<a href="#/applications"><div class="viewByAppl"></div></a>
</div>
<script type="text/ng-template" id="appls.html">
<div sample class="appls myElement" ng-repeat="app in appData">
<a href=#/applications/{{app.uri}}>
<div>
<img ng-src="{{app.imageS}}"/>
{{app.name}}
</div>
</a>
</div>
</script>
JS -
app.directive('sample', function () {
return {
restrict: 'A',
transclude: false,
link: function (scope, element, attributes) {
element.on('click', function () {
$(element).trigger("myEvent.sample");
});
},
};
});
$(document).ready(function () {
$('img').on('dragstart', function (event) { event.preventDefault(); });
$(".myElement").on("myEvent.sample", function (e) {
alert('clicked!');
console.log("made it");
});
});
I'd like to think that I am using directives correctly, but I am fairly new to Angular and I'm sure I'm using it incorrectly with Jquery.
Upvotes: 0
Views: 587
Reputation: 54741
Try adding the following to your document.ready(..)
function.
console.log('sample count: '+$(".myElement").length);
I think you'll find that it prints sample count: 1
to the console.
In your template you have
<div sample class="appls myElement" ng-repeat="app in appData">
The ng-repeat
directive creates additional DOM elements, but this happens during an Angular digest cycle. Which is happening after the document ready is executed.
If you want to broadcast custom jQuery events from AngularJS. Pick a DOM element that you know exists.
In your directive change to this
$('body').trigger('myEvent.sample', $(element));
Now you can catch the event elsewhere in your JavaScript.
$('body').on('myEvent.sample',function(event, element){
console.log("made it");
console.log(element); // the argument for the event.
});
Upvotes: 3