嵌套指令不能按预期工作

时间:2013-10-02 08:27:55

标签: angularjs angularjs-directive

我有一个通用指令

  • genericDirective

应该选择另一个特定的指令

  • type1指令obj.type == "type1"
  • type2指令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>",
    };
});

输出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>

知道为什么这些没有被实际指令取代?

2 个答案:

答案 0 :(得分:2)

使用return中的genericDirective

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

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

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

要阅读有关编译和链接的更多信息,请参阅docs here。标题为“编译过程和指令匹配”的部分非常有用。

答案 1 :(得分: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);
        }
     };
});
相关问题