【问题标题】:Prevent ng-if to print html template in angular js component防止 ng-if 在 Angular js 组件中打印 html 模板
【发布时间】:2018-07-28 16:06:37
【问题描述】:

我有以下组件,我需要在代码中的几个地方不显示该组件,但我不想在组件之外这样做,因为我需要在不同的地方添加 ng-if 以检查是否status 为 1 则不显示指令。

如何在组件中做到这一点?也许我需要一个控制器然后不打印 HTML?

我不想使用 ng-if,因为我也在尝试减少观察者的使用

组件:

  .component('comp', {
        template: '<span class="class"><another-component></nother-component></span>' +
                  '<span class="status {{$ctrl.textClass}}" ng-bind-html="$ctrl.text" ></span>',
        bindings: {
            textClass : '<',
            text : '<'
            status : '<'
        }
    });

【问题讨论】:

  • 所以向组件添加另一个bindings 以获取当前状态并将其从使用组件的位置传递到内部组件,然后将ng-ifstatus 一起使用
  • 这是一个好习惯吗?你的意思是在组件模板中添加 ng-id 而不是 outsise
  • 这就是你想要的!这可以帮助您在没有ng-if 的视图中插入组件,不是吗?

标签: angularjs components


【解决方案1】:

您可以在组件的控制器中注入 $element,然后根据某些条件(无论符合您的规范)删除元素。

例如

  .component('someComponent', {
    controller: someComponentController,
    template: 'Hi'
  })

someComponentController.$inject = ['$element'];

function someComponentController($element) {
  const earthIsRounded = true;
  if (earthIsRounded) {
    $element.remove();
  }
}

Some working fiddle you can play around with.

【讨论】:

    猜你喜欢
    • 2017-05-13
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多