从 angularjs 指令触发点击事件 [英] trigger click event from angularjs directive

查看:98
本文介绍了从 angularjs 指令触发点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为从 angularjs 指令指定索引的 li 元素触发点击事件?我曾尝试使用 $first 来触发第一个元素的点击,但它不起作用.

How can i trigger a click event for li elements specifying their index from the angularjs directive? I have tried using $first for triggering click for the first element, but its not working.

感谢您的帮助.

推荐答案

这可能是您实现这一目标的不同方式.将索引和项目都传入指令,让指令在模板中设置 html:

Here is perhaps a different way for you to achieve this. Pass into the directive both the index and the item and let the directive setup the html in a template:

演示:http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview

html:

<ul id="thumbnails">
    <li class="thumbnail" ng-repeat="item in items" options='#my-container' itemdata='item' index="$index">

    </li>
  </ul>

js 指令:

app.directive('thumbnail', [function() {
  return {
    restrict: 'CA',
    replace: false,
    transclude: false,
    scope: {
        index: '=index',
        item: '=itemdata'
    },
    template: '<a href="#"><img src="{{item.src}}" alt="{{item.alt}}" /></a>',
    link: function(scope, elem, attrs) {
        if (parseInt(scope.index) == 0) {
            angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
        }

        elem.bind('click', function() {
            var src = elem.find('img').attr('src');

            // call your SmoothZoom here
            angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
        });
    }
}
}]);

如另一个答案中指出的那样,您可能最好为图像添加 ng-click.

You probably would be better off adding a ng-click to the image as pointed out in another answer.

更新

演示链接不正确.它已更新为:http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview

The link for the demo was incorrect. It has been updated to: http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview

这篇关于从 angularjs 指令触发点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆