gpt4 book ai didi

javascript - 如何在声明后运行 DOM 添加的指令?

转载 作者:行者123 更新时间:2023-12-03 10:52:13 26 4
gpt4 key购买 nike

我想在声明指令后添加 DOM,但不适用于将来的使用。请检查我的代码:

http://jsfiddle.net/uh99z0uL/1/

angular.element(document).ready(function(){
angular.bootstrap(document, ["MyApp"]);
});

var MyApp = angular.module("MyApp", []);
MyApp.directive('user', function($rootScope){
var directive = {};
directive.restrict = 'E';
directive.template = "I'm {{name}}!";
directive.controller = function($scope){
//$scope.name = "Jack";
};
directive.scope = {
name: '@'
};
directive.compile = function($element, attributes) {
$element.addClass("show");
return function($scope, $element, attributes) {
};
};
return directive;
});

//This works...
angular.element(document.documentElement).append('<user name="Jack" />'); //ok

//Now I want to run the same but adding the DOM after declaring the directive
setTimeout(function(){
angular.element(document.documentElement).append('<user name="Carl" />'); //no
//not working...
},2000);

这些新元素有可能在声明后运行该指令吗?谢谢兄弟们。

最佳答案

在附加之前必须使用 $compile

 angular.element(document.documentElement).append($compile('<user name="Carl" />')($scope));

http://jsfiddle.net/codingninja/amch7rpy/2/

关于javascript - 如何在声明后运行 DOM 添加的指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com