2017-02-17 50 views
0

是否有可能为angularJS 1.6中的组件定义可变模板? 事情是这样的:angularJS - 可变组件模板

<div class="test"> 
    <{{$ctrl.GetElement()}}> 
</div>   

在这我想在运行时的模板是什么样的判案。

有没有办法做到这一点?

+0

你可能会寻找'$ compile' https://docs.angularjs.org/api/ng/service/$compile – Akis

+0

这是可能的,但是是完全反对的角度设计目标。这是Directives和Components的领域;这种带有执行内部表达式的函数的代码将会明智地影响您的应用性能。 – Claies

回答

1

下面是使用$compile的“可变模板”的一个简单示例。让我们定义一个“发电机”指令,它就能产生其他指令:

app.directive('createDirective', function($compile) { 
    return { 
     scope: { 
      directiveName: '@' 
     }, 
     link: function(scope, element) { 
      var newHtml = '<' + scope.directiveName +'></ '+ scope.directiveName +'>'; 
      element.append($compile(newHtml)(scope)); 
     } 
    }; 
}); 

这种“发电机”指令需要在一个字符串(通过属性“指令名”),组装新的HTML,编译它,并将生成的HTML附加到生成器指令中。

我已经定义了一个名为“你好”的单独指导,这是我想从发电机指令动态调用:

app.directive('hello', function() { 
    return { 
     restrict: 'E', 
     link: function(scope, element) { 
      element.append("Hello!"); 
     } 
    } 
}); 

现在,我们可以用生成器指令编制了“你好”指令

<div create-directive directive-name="hello"></div> 

这导致这个生成的HTML

<hello class="ng-scope"> 
    <!-- hello--> 
    Hello! 
</hello> 

在此外,我们可以以类似的方式从控制器到发电机指令传递一个变量:

app.controller('MainCtrl', function($scope) { 
    $scope.newDirective = "from-controller"; 
}); 

而在HTML:

<div create-directive directive-name="{{newDirective}}"></div> 

一定要看一看的$compile documentation

Demo