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

查看:889
本文介绍了从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 +')'});
        });
    }
}
}]);

如果在另一个答案中指出,您可能会更好地添加点击图标。

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天全站免登陆