0

I have a generic directive

  • genericDirective

that is supposed to choose another specific directive

  • type1 directive if obj.type == "type1"
  • type2 directive if obj.type == "type2"

HTML

<div ng-controller="MainCtrl">
    <div class="genericdirective" ng-repeat="obj in someArray"></div>
</div>

Javascript

var app = angular.module("myApp", []);

app.controller("MainCtrl", function ($scope) {
    $scope.someArray = [
        {type:"type1",title:"lorem"},
        {type:"type2",title:"ipsum"},
        {type:"type2",title:"dolor"}
    ];
});
app.directive("genericdirective", function(){
    return{
        restrict: "C",
        template: "<div class='{{obj.type}}'>genericdirective</div>"
    };
});
app.directive("type1", function(){
    return{
        restrict: "C",
        template: "<div>type1</div>"
    };
});
app.directive("type2", function(){
    return{
        restrict: "C",
        template: "<div>type2</div>",
    };
});

Output HTML

<div class="genericdirective ng-scope" ng-repeat="obj in someArray">
    <!-- Not replaced by the actual directive -->
    <div class="type1">genericdirective</div>
</div>
<div class="genericdirective ng-scope" ng-repeat="obj in someArray">
    <!-- Not replaced by the actual directive -->
    <div class="type2">genericdirective</div>
</div>
<div class="genericdirective ng-scope" ng-repeat="obj in someArray">
    <!-- Not replaced by the actual directive -->
    <div class="type2">genericdirective</div>
</div>

Any idea why these are not replaced by the actual directives?

4

2 回答 2

2

基于 Davin 的回答,如果您将指令更改为此它应该可以工作:

app.directive("genericdirective", function($compile){
    return{
        restrict: "C",
        link: function (scope, element, attrs) {
           element.append('<div class="' + scope.obj.type + '">genericdirective</div>');
           $compile(element.contents())(scope);
        }
     };
});
于 2013-10-02T09:00:02.943 回答
2

通过return在您的genericDirective:

app.directive("genericdirective", function(){
    return{
        restrict: "C",
        template: "<div class='{{obj.type}}'>genericdirective</div>"
    };
});

您正在返回该link功能。链接阶段发生在编译阶段之后。因此,当您解析此模板时,angular 无法“编译”您的子指令然后链接它们。

您需要定义一个编译函数并在那时设置指令,以便修改 Angular 将考虑的 html。任何时候您需要在链接之前操作 html 时$scope,您可能都希望在编译阶段进行更改。

要阅读有关编译和链接的更多信息,请参阅此处的文档。标题为“编译过程和指令匹配”的部分非常有帮助。

于 2013-10-02T08:33:16.213 回答