我正在尝试创建一个自定义指令,它以类似于在jQuery中执行它的方式构建DOM。但是,我无法让它发挥作用。 AngularJS的element.append()删除传递给它的字符串中的所有HTML。到目前为止,这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js">
</script>
</head>
<body ng-app="myapp">
<div ng-controller="myController">
<table tasklist="123">
</table>
</div>
<script>
var module = angular.module("myapp", []);
module.directive('tasklist', function($compile) {
var directive = {};
directive.restrict = 'EA'; /* restrict this directive to attributes */
directive.link = function($scope, element, attributes) {
console.log("directive link() running");
// Add tr rows inside table element.
// You can use jQuery DOM methods on the element object.
for( var i=0; i < $scope.data.taskList.length; i++) {
var rowStr = "<tr><td>" + $scope.data.taskList[i].taskTitle + "</td></tr>";
$compile(rowStr)($scope, function(cloned, scope) {
element.append(cloned);
});
}
}
return directive;
})
var myController = module.controller("myController", function($scope) {
console.log("myController running") ;
$scope.data = {};
$scope.data.taskList = [];
$scope.data.taskList.push({ taskId : "1", taskTitle : "First task 1"});
$scope.data.taskList.push({ taskId : "2", taskTitle : "Second task"});
$scope.data.taskList.push({ taskId : "3", taskTitle : "Third task"});
});
</script>
</body>
</html>