angularjs - 从自定义指令设置元素 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 不起作用。
解决方案
您需要在将插入的 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>
推荐阅读
- wpf - 仅 UI 元素的全球化
- wildfly - OpenId django-oidc-provider 使用 keycloak 适配器在 Wildfly 中进行身份验证 - 无法解析 JWT
- javascript - 删除 iframe 中的 header.html
- jenkins - 如何自动检查更新的 Jenkins 插件版本?
- html - 如何在不破坏固定元素定位的情况下使用 css 过滤器创建暗模式?
- linux - 循环连续粘贴到文件而不覆盖
- python - 如何处理库 API 的更改以避免破坏 Python 中的用户代码
- selenium - 访问工具提示 selenium python 后面的元素文本
- bioinformatics - conda 'ResolvePackageNotFound' 错误,尽管我将所有文件都安装在同一路径中
- google-developers-console - 在 Playstore 控制台中更新现有开发者帐户名称