添加ng-click到离子项目中的所有<img/>

时间:2017-04-24 22:10:52

标签: angularjs ionic-framework ionic2 angular-directive

我真的是离子和角度的新手,我需要添加每个img元素ng-click属性。我试图使用$ compile但我总是遇到一些错误问题,比如

  

RangeError:超出最大调用堆栈大小

HTML

 <img src="img/VIyNbAJ8TbeAQQo6Nm3m_Pic1.PNG"  style="display: block; width: 100%; height: auto; margin-left: auto; margin-right: auto;">

controllers.js

.controller('modalCtrl', function($scope, $ionicModal, $compile) {

$ionicModal.fromTemplateUrl('templates/modal.html', {
    scope: $scope
}).then(function(modal) {
    $scope.modal = modal;
});

$scope.openModal = function (event) {
    $scope.modal.show();
    $scope.imgUrl = event.target.src;
} 

directives.js

.directive('img', function ($compile) {
return {
    restrict: 'E',
    link: function (scope, element) {

        element.attr('ng-click', "openModal($event)" );

        $compile(element)(scope);
    }
};

如何在每个img中自动点击ng-click? Tnx你。

1 个答案:

答案 0 :(得分:0)

不是编译ng-click指令,只需添加一个点击处理程序:

app.directive('img', function ($compile) {
return {
    restrict: 'E',
    link: function (scope, element) {

        //element.attr('ng-click', "openModal($event)" );
        //$compile(element)(scope);

        element.on("click", function(event) {
            scope.$eval("openModal($event)", {$event: event});
            scope.$apply();
        });
    }
};