0

I have the following partial being inserted into an ng-view. I'm only pasting the part of the partial that is relevant.

<tr ng-repeat="group in groups">
    <td><a href="" class="restaurant-group-edit" create-link>{{ group.name }}</a></td>
    <td>{{ group.members.length }}</td>
    <td>{{ 5 }}</td>
    <td style="text-align: right">
    <span class="pseudo-select enhanced-select ps-settings">
        <select class="enhanced-select ps-settings restaurant-group-select" restaurant_group_id="1">
            <option value="actions">Actions</option>
            <option value="edit">Edit</option>
            <option value="edit">Restaurants</option>
            <option value="delete">Menus</option>
            <option value="edit">Delete</option>
        </select>
        <span class="es-label">Actions</span>
        <span class="icon"></span>
    </span>
    </td>
</tr>

I would like to bind a click event to each of the anchor elements above. I've tried this with a custom directive named create-link. In my app.js file I have the following code.

adminApp.directive("create-link", function($location, $timeout, $rootScope) {
    console.log("I fired the directive!");
    return {
        restrict: "A",
        link: function(scope, element) {
            $timeout(function(){
                element.on("click", function(e) {
                    console.log("Clicked!");
                });
            });
        }
    };
});

However, the event is never bound. In fact, the "I fired the directive!" never actually gets written to the console. What am I missing here? Binding events to DOM elements that are created while loading the view would seem to be a common use case. Surely there is an easy way to go about doing it.

Thanks for any help.

Andrew

1
  • Use e.preventDefault() Commented Jul 13, 2015 at 9:37

1 Answer 1

2

Change the directive name in js to the camelcased version of your directive name declared in view part:

adminApp.directive("createLink", function($location, $timeout, $rootScope) {
    console.log("I fired the directive!");
    return {
        restrict: "A",
        link: function(scope, element) {
            $timeout(function(){
                element.on("click", function(e) {
                    console.log("Clicked!");
                });
            });
        }
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It's the little things that get you. :-)

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.