search

Home  >  Q&A  >  body text

angular.js - How to bind events to child elements in templates in angular directives?

directive('mzIconTransform',['$timeout',function ($timeout) {
    return {
        scope: {
            iconSrc1: '@',
            iconSrc2: '@',
            showFlag: '=',
            clickFunc: '&'
        },
        restrict: 'EA',
        replace: true,
        transclude: true,
        template: '<p><img src="{{iconSrc1}}"  class="icon-button" ng-if="!showFlag" id="icon-off" /><img src="{{iconSrc2}}" class="icon-button" ng-if="showFlag" ng-click="clickFunc()" /></p>',
        link: function (scope, element, attr) {
            var elemChildren = element.children();
            element.bind('touchstart', function () {
                scope.$apply(function () {
                    scope.showFlag = true;
                });
                console.log("touchstart事件触发");
            });
            element.bind('touchend', function () {
                scope.$apply(function () {
                    scope.showFlag = false;
                });
                console.log("touchend事件触发");
            });
        },
    };
}] );

The function I want is that after touching the picture, the picture will change to another one, and then change back again after the touch is completed. At the same time, the method in ng-click will be called, so I want to add the first img under p event, but it seems that the child element cannot be obtained in the link function. Is there any way to obtain the child element and bind events to it at the same time

漂亮男人漂亮男人2793 days ago677

reply all(3)I'll reply

  • 滿天的星座

    滿天的星座2017-05-15 17:10:16

    element.find('img')[0] Can you get it?

    reply
    0
  • 某草草

    某草草2017-05-15 17:10:16

    Modify the template in compile
    compile:function(iEle,iAttr){
    //jquery Get the img tag under the iEle element of the template
    $('img',iEle).attr('someAttr','someValue');/ /Modify an element attribute of the template, and naturally you can modify ng-click
    }

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-15 17:10:16

    Hello, have you solved this problem? Please solve it

    reply
    0
  • Cancelreply