首页 > 解决方案 > 从自定义指令设置元素 html 时,data-ng-click 不起作用

问题描述

我有一个自定义指令来显示内容,具体取决于它是否被标记为特殊:-

    myApp.directive('actionSpace', function() {
    //define the directive object
    var directive = {};

    //restrict = E, signifies that directive is Element directive
    directive.restrict = 'E';

    directive.link = function(scope, elem, attr) {
        console.log(scope.typeEv);
        if(attr.special == "1") {
            elem.html("");
        } else {
            elem.replaceWith('<div class="event-list-control"><button class="event-action-btn" data-ng-click="whoWas()"> '+
                        '<i class="fas fa-edit"></i>' +
                        '</button><button class="event-action-btn" data-ng-click="tellMe()">' +
                        '<i class="fas fa-trash-alt"></i></button></div>');
        }
    }
    return directive;
    });

我可以在控制台指令的父范围中看到可用(它打印变量之一),但 data-ng-click 不起作用。

标签: angularjs

解决方案


您需要在将插入的 html 插入元素之前对其进行编译,请参考以下示例。我用$compile方法制作data-ng-click作品!

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope) {

});

app.directive('actionSpace', function($compile) {
    //define the directive object
    var directive = {};

    //restrict = E, signifies that directive is Element directive
    directive.restrict = 'E';

    directive.link = function(scope, elem, attr) {
        var html = ''
        scope.tellMe = function(){console.log("telling");}
        scope.whoWas = function(){console.log("this is");}
        if(attr.special == "1") {
            html = '';
        } else {
            html = '<div class="event-list-control"><button class="event-action-btn" data-ng-click="whoWas()">'+ '<i class="fas fa-edit"></i>' +
                        'Who Was</button><button class="event-action-btn" data-ng-click="tellMe()">' +
                        '<i class="fas fa-trash-alt"></i>Tell Me</button></div>';
        }
        var el = $compile(html)(scope);
    
        elem.append(el);
    }
    return directive;
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
    <action-space></action-space>
</div>


推荐阅读