2015-02-08 27 views
0

我想在声明一个指令后添加DOM,但不适用于将来的使用。请检查我的代码:如何在声明后运行由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); 

这将是可能的,这些新的元素可能会运行已被宣布后的指令?谢谢兄弟。

+0

你有附加 – CodingNinja 2015-02-08 06:55:22

+0

第一个作品,因为它引导前执行之前编译之前,使用$编译。在引导函数被调用后 - 你必须在插入到dom之前编译你的HTML。 – lujcon 2015-02-08 07:30:21

+0

@lujcon可以在控制器之外$编译元素? – 2015-02-08 07:33:52

回答

1

你有附加

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

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

+0

这是可能的编译没有控制器?我想要做的是不显示任何HTML代码。谢谢 – 2015-02-08 07:22:49

+0

嗯..更新了答案。使用运行而不是控制器 – CodingNinja 2015-02-08 07:32:49