0

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.

1 Answer 1

3

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.
  });
Sign up to request clarification or add additional context in comments.

2 Comments

When you say I should destroy the event, I should do this in my controller, correct?
@Xogle ignore that and I removed it from my answer. When you bind an event listener to something outside of the directive. You have to unbind it when $destroy is called, but I forgot you were calling trigger and not binding anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.