我使用按钮以javascript DOM方式创建元素如下
var app = angular.module('app', []);
function createElement2(resource){
el= document.createElement('textarea');
$(el).attr('ID', "Textbox0");
$(el).attr('type', "text");
$(el).attr('value', "Textbox0");
$(el).attr("name","Textbox0");
$(el).attr("ng-model", "html");
//this line will be diffrent for element
document.getElementById("areaT").appendChild(el)
}
app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
console.log("test")
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
function MyController($scope) {
$scope.click = function(arg) {
alert('Clicked ' + arg);
}
$scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}
问题是我想要一个标签自定义指令Angluarjs用任何元素创建不同的验证和dirctive代码只在页面加载时执行。换句话说我想在每次创建元素时执行下一段代码< / p>
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<h1>Compile dynamic HTML</h1>
<div id="areaT" ng-controller="MyController">
<textarea ng-model="html"></textarea>
<div dynamic="html"></div>
</div>
<input type="button" onclick="createElement2(this)">
</body>
</html>
请注意,当输入任何代码时,html代码中的textarea将会执行console.log(“test”)等等。当我在其中输入文本时点击按钮时,我需要的是将添加的textarea执行html代码中的textarea执行(console.log(“test”)等等)