简体   繁体   English

声明后如何运行由DOM添加的指令?

[英]How to run a directive added by DOM after declaring?

I want to add DOM after declaring a directive, but does not work for a future use. 我想在声明指令后添加DOM,但以后无法使用。 Please, check my code : 请检查我的代码:

http://jsfiddle.net/uh99z0uL/1/ 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);

It would be possible that these new elements may run the directive after have been declared?. 这些新元素可能会在声明?之后运行指令。 Thanks brothers. 谢谢兄弟们。

you have to use $compile before appending 您必须在附加之前使用$ compile

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM