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

时间:2015-02-08 06:32:35

标签: javascript angularjs angularjs-directive

我想在声明指令后添加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);

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

1 个答案:

答案 0 :(得分:1)

你必须在追加

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

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