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