指令的动态模板,包装器和内部元素的不同解析行为

Dynamic template of a directive, different resolving behaviour for wrapper and inner elements

本文关键字:元素 内部 动态 包装 指令      更新时间:2023-09-26

我已经用angular工作了几个月了,距离我进入指令只有一周左右的时间了。今天,我在尝试构建一个复选框字段依赖于另一个的设置页面时遇到了这个小怪癖(如中所示,只有在选中了另一个复选栏字段时才会显示)。

我发现有ng残疾人可以工作,但我想如果另一个没有勾选,我宁愿隐藏整个字段,+我想我可以在原始html上使用ng show来做到这一点,但我对指令非常着迷,我想从内部了解它是如何做到的。

所以,这是HTML:

<form>
  <input type="checkbox" data-ng-model="mdl.show" />
  <span>Switches 'mdl.show' on and off, now it's {{mdl.show}}</span>
  <div spg dependent="mdl.show"></div>
</form>

控制器:

app.controller('appCtrl',['$scope',
  function($scope){
    $scope.mdl = {show: true};
  }
])

指令:

app.directive('spg',function(){
  return {
    restrict: 'A',
    compile: function (element,attrs){
        var html = '<div data-ng-show="' + attrs.dependent + '">';
        html += '<p data-ng-show="' + attrs.dependent + '">This text doesn''t show if dependent resolves to false</p>';
        html += '<p>For some reason, even though div wrapper has the same configuration as the previous ''p'' - this one will show either way</p>'
        html += '</div>';
        angular.element(element).replaceWith(html);
    }
  }
})

这就是那个混蛋。比起得到这个问题的解决方案,我更愿意理解为什么会发生这种情况。尽管两者都很受欢迎。谢谢

编辑:1.0.7和1.2.0rc1的行为相同。

我不知道为什么你的代码不起作用,但我知道你不需要使用compile函数,除非你的指令进行模板转换,而自定义指令很少需要模板转换。大多数指令只需要实现link函数和/或controller函数。

在您的情况下,指令不需要任何指令即可工作。以下代码运行良好:

app.directive('spg',function(){
  return {
    restrict: 'A',
    scope: { visible: '=' },
    template: '<div ng-show="visible">' +
              '<p>This text doesn''t show if dependent resolves to false</p>' +
              '<p>For some reason, even though div wrapper has the same configuration as the previous ''p'' - this one will show either way</p>' +
              '</div>',
  };
});

Plunker在这里。

也许这个答案不是你所期望的,但我认为这个问题尤其不值得担心。如果您想了解更多关于compile函数的信息,这篇文章应该会让您入门。开发指南中也包含一些有价值的信息。