【问题标题】:Nested directives don't work as expected嵌套指令未按预期工作
【发布时间】:2013-10-02 08:27:54
【问题描述】:

我有一个通用指令

  • 通用指令

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

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

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

知道为什么这些不被实际指令替换吗?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    通过在您的genericDirective 中使用return

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

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

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

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

    【讨论】:

    • 你实际上可以在链接函数中编译,它可以让你直接访问范围和你的 obj.type 值,通过在你的指令中注入 $compile ,我在这里做了一个简单的例子:@987654322 @
    • 谢谢你的例子,它工作得很好,我不需要再阅读文档了(好吧,我会读它以防万一^^)。
    • 事实上,指令开发者指南是你必须再读一遍的东西。
    【解决方案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);
            }
         };
    });
    

    【讨论】:

    • 我选择了 Davin 的答案,因为他在 cmets 中发布了一个示例,但感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多