【问题标题】:AngularJs Directive - Re render html when adding new angular attributeAngularJs 指令 - 添加新的角度属性时重新渲染 html
【发布时间】:2016-01-08 08:35:54
【问题描述】:

我的问题基本上是让编译器获得我在指令中添加的新属性。 我正在使用打字稿,我有这样的东西。

public class MyDirectiveScope: ng.IScope
{
    foo: boolean;
}

public class MyDirective implements ng.IDirective
{        
    public restrict = 'A';

    public scope = {
        foo:'=',

    };

    public constructor (protected $log: ng.ILogService)
     {

     }

    link = ($scope: MyDirectiveScope, element: JQuery, attributes: ng.IAttributes)
    {
        if(!$scope.foo)
        angular.element(element).attr("ng-if","false");
    }
}

我调用指令的元素获取了我添加的新属性,但 angular 没有评估这个新属性。例如,如果我有一个 <div> 元素获取这个新属性并且类似于 <div ng-if="false">, 我希望不会显示 div 内的内容。

我在 angular.element(element).css("display", "none") 之前使用过,这很有效,但我真的希望 div 元素根本不在 DOM 中。

【问题讨论】:

  • 尝试在指令构建的编译阶段而不是链接。

标签: angularjs html angularjs-directive typescript


【解决方案1】:

应避免动态设置指令属性,这肯定违背了最佳实践。您应该在模板中使用<div ng-if="checkCondition">,并且可以修改checkCondition 函数中的逻辑。即使有一些可能的属性,您也应该将它们全部添加到元素中并将逻辑放在函数中。

如果您必须使用这种方法,您可以使用您需要的属性销毁并重新创建指令,如下所示:

var element = $compile("<my-directive someAttribute=\"someval\"")($scope);

然后,您可以将 element 添加到您的 DOM 中,但您认为合适。

【讨论】:

  • 嗯,我明白了,我使用我的指令作为属性,所以我有类似
    的东西,在使用 $compile 函数后替换我的属性我必须做类似元素的事情.replaceWith() 对吗?
猜你喜欢
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 2015-08-04
  • 2017-02-01
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
相关资源
最近更新 更多