JavaScript / AngularJS:我如何从javascript声明指令?

时间:2016-04-06 22:22:03

标签: javascript jquery html angularjs angularjs-directive

我需要在javascript中声明我的html标签(angular指令),如下所示。我如何处理正确的js语法。

$scope.myList =[ {title='Angular1' content='<div angular-one></div>'},

                 {title='Angular2' content='<div angular-two></div>'}];

我稍后会将此值绑定回html。我只是想知道如何使用javascript在div标签内声明angular-one和angular-two指令。

在html中,我将从javascript调用传递的值并在html中绑定指令。

{{content}}

我的指令显示为字符串而非绑定为html。

1 个答案:

答案 0 :(得分:1)

非常简单,只需要创建一个简单的指令来编译html(使用角度来自$ compile的服务):

.directive('compile', ['$compile', function ($compile) {
    return function(scope, element, attrs) {
        scope.$watch(
            function(scope) {
                // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
            },
            function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);

                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
            }
        );
    };
}]) 

您可以在此处查看一个有效的示例:https://jsfiddle.net/scyrizales/zu2osuzb/