自定义指令可以用包含ng-show的模板替换其元素吗?

时间:2013-09-05 15:01:41

标签: javascript angularjs angularjs-directive ng-show

我想构建一个简单的hello指令,如下所示:

<hello foo="bar"></hello>

如果foo属性等于“bar”,我想用<div ng-show="true"></div>"替换元素;否则,将其替换为<div ng-show="false"></div>"。但是,我只想替换hello元素,而不是嵌套在其中的任何子元素!

例如:

<hello foo="bar">
  <h1>Hi everyone!</h1>
</hello>

将被替换为:

<div ng-show="true">
  <h1>Hi everyone!</h1>
</div>

这甚至可以吗?

3 个答案:

答案 0 :(得分:2)

您可以通过使用包含来实现这一目标:

<强>的Javascript

app.directive('hello', function() {
  return {
    restrict: 'E',
    transclude: true,
    replace: true,
    scope: { foo: '@' },
    template: '<div ng-show="foo == \'bar\'" ng-transclude></div>',
  };
});

<强> HTML

<hello foo="bar">
  <h1>Hi everyone!</h1>
</hello>

<hello foo="baz">
  <h1>Hi everybody!</h1>
</hello>

使用Plunker here

答案 1 :(得分:1)

在编译/链接另一个指令时动态注入指令是一项繁琐的工作。您不能简单地设置属性,因为它不会被Angular收集。手动编译无效,因为它会导致无限循环。话虽如此,如果您已经确定这是您想要的:),请转到:

app.directive('hello', function($injector) {
  return {
    transclude: true,
    replace: true,
    restrict: "E",
    template: "<div ng-transclude></div>",
    compile: function(tele, tattrs) {
      var ngShow = $injector.get("ngShowDirective")[0];
      return function(scope, ele, attrs) {
        attrs.$set("ngShow", (attrs.foo === "bar").toString());
        ngShow.link(scope, ele, attrs);
      }
    }
  }
});

这个想法是手动链接ngShow指令而不是依赖AngularJS来做到这一点。通常,只有AngularJS会调用compilelink;此外,此代码依赖于ngShow具有link函数的知识。一般来说,它应被视为黑客并谨慎使用。

Demo link

答案 2 :(得分:0)

您应该只能将ng-show属性应用于hello元素,并检查模型的属性以确定它是否应隐藏。

<hello ng-show="foo == 'bar'">
    <h1>Hi everyone!</h1>
</hello>

在此视图可访问的范围内,您将拥有foo属性。

$scope.foo = 'bar';