使用angular.element()将元素插入DOM的正确方法是什么?
app.directive('validationTest', function(){
return {
restrict: 'A',
replace: false,
link: function(scope, element, attrs){
scope.call = function(){
console.log('Someone clicked it');
};
var newElement = angular.element('<span ng-click="call()">').text('Yo Yo');
element.append(newElement);
}
};
});
在这段代码中,我试图在已应用指令的元素中添加span元素。我能够将此span元素添加为调用append mehtod的父div的子元素。
但是,正如您在代码中看到的那样,ng-click
也与此范围相关联。我知道从任何角度来看它都没有用,它仅用于演示目的。因此,通常,单击此跨度,应在控制台中打印一行。但是,它不会发生。
我在这里缺少什么?我是否对此追加使用了错误的方法,或者我的代码中有错误?
答案 0 :(得分:2)
如果您动态附加到DOM的HTML具有指令,那么您需要在编译并链接它之前将其附加到DOM:
var newElement = angular.element('<span ng-click="call()">').text('Yo Yo');
$compile(newElement)(scope);
element.append(newElement);
一种不易出错的替代方法是将DOM操作移动到编译函数。通过在编译阶段插入新元素,新的HTML将在链接阶段自动链接(无需手动编译/链接):
app.directive('myDirective', function() {
return {
compile: function(element, attr) {
var newElement = angular.element('<span ng-click="call()">').text('Yo Yo');
element.append(newElement);
return function(scope, element, attr) {
}
}
}
});
答案 1 :(得分:1)
您缺少角度编辑。编译遍历您的DOM以查找指令并初始化它们。没有调用编译,没有任何东西会初始化你的ngClick。试试这个使用$ compile:
app.directive('validationTest', ['$compile', function($compile){
return {
restrict: 'A',
replace: false,
link: function(scope, element, attrs){
scope.call = function(){
console.log('Someone clicked it');
};
var newElement = angular.element('<span ng-click="call()">').text('Yo Yo');
element.append(newElement);
$compile(element)(scope);
}
};
});
有关详细信息:https://docs.angularjs.org/api/ng/service/ $ compile
答案 2 :(得分:0)
最好使用templateUrl
或template
。