我有这样的代码:
$scope.printOutRowModel = function(){
console.log("blah");
}
$scope.createTable = function(name)
{
var element = angular.element(document.querySelector('.popup'));
var content = "";
content+='<div><hr/>';
content+='<h4>'+name+'</h4>';
content+='<table><thead>';
var columnName = Object.keys($scope.genericModel[name][0]);
for(var i=0; i<columnName.length; i++)
{
if(columnName[i] != "$$hashKey")
{
content+='<th>'+columnName[i]+'</th>';
}
}
content+='</thead><tbody>';
for(var j=0; j<$scope.genericModel[name].length; j++)
{
content+='<tr>';
var value = Object.values($scope.genericModel[name][j]);
for(var i=0; i<value.length-1; i++)
{
content+='<td>'+value[i]+'</td>';
}
content+='</tr>';
value = null;
}
content+='</tbody></table></div>';
element.html(content);
}
所以现在我要做的是添加&#39; ng-click =&#34; printOutRowModel()&#34;&#39;生成的&#34; td&#34;元素。我尝试了多种方法,但我没有工作。当我将它添加到我的index.html中已有的任何其他元素时,它确实有效。所以我猜测这个生成的HTML不是&#34;编译的&#34;在范围或什么。有没有办法做到这一点?
答案 0 :(得分:0)
将此指令添加到您的应用中:
app.directive('template', ['$compile', function($compile) {
return function(scope, element, attrs) {
attrs.$observe("template", function(_newVal) {
scope.$applyAsync(function() {
element.html(_newVal);
$compile(element.contents())(scope);
});
});
};
}]);
然后,不要在.popup
函数中选择createTable
类,而是执行此操作:
<div class="popup" template="{{myTableTpl}}"></div>
并将您的功能更改为:
$scope.createTable = function(name)
{
var content = "";
// Create your content...
$scope.myTableTpl = content;
}
<!doctype html>
<html ng-app="app">
<body ng-controller="ctrl">
<div template="{{tpl}}"></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
angular.module('app', [])
.directive('template', ['$compile',
function($compile) {
return function(scope, element, attrs) {
attrs.$observe("template", function(_newVal) {
scope.$applyAsync(function() {
element.html(_newVal);
$compile(element.contents())(scope);
});
});
};
}
])
.controller('ctrl', function($scope) {
$scope.tpl = '<h1>METE-30</h1>'
});
</script>
</body>
</html>