简体   繁体   中英

AngularJS - Bind click event to element

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

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!");
                });
            });
        }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM