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

时间:2013-08-22 20:21:18

标签: javascript angularjs angularjs-directive

现在已经和棱镜一起工作了几个月,自从我投入指令以来已经只有一个星期了。今天我在尝试构建一个设置页面时遇到了这个小怪癖,其中一个复选框字段依赖于另一个(如图所示,只有在选中了另一个复选框字段时才显示)。

我发现有可以使用的ng-disabled,但我想我宁愿隐藏整个字段,如果另一个没有被抓,+我想我可以在原始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);
    }
  }
})

here's插入。 除了接收这个问题的解决方案之外,我更愿意理解为什么会发生这种情况。虽然两者都非常受欢迎。感谢。

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

1 个答案:

答案 0 :(得分:0)

我不知道为什么你的代码不起作用,但我知道你不需要使用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 here

也许这个答案不是你所期待的,但我认为这个问题尤其不值得担心。如果您想了解有关compile功能的更多信息,this文章可以帮助您入门。 dev guide也有一些有价值的信息。