如何使用AngularJS加载动态指令内容?

时间:2016-05-30 12:56:18

标签: angularjs typescript

我很难尝试使用Angular实现动态加载的内容...我有几个小部件,并且在请求之后通过绑定加载了它们的partialName变量。这就是我在下面使用scope.$watch的原因。即使模板设置了正确的内容,视图本身也不会刷新以显示适当的内容。我尝试了下面$broadcast之类的事,没有运气。我怎样才能做到这一点?谢谢!

export class CioTemplateLoader implements ng.IDirective {
  public template: string;
  public partials: { [id: string]: string; } = {};
  public scope = {
    partialName: '='
  };
  public route: any;

  static $inject = [
    '$route'
  ];

  constructor(){//$route: any) {
    // this.route = $route;
    this.partials['claimOverview'] = require('../../claims/claim-overview.html');
    //...
  }

  link = (scope: ng.IScope, elem: JQuery, attributes: ng.IAttributes) => {
    var that = this;
    scope.$watch('partialName', function (value: string) {
      if (value) {
        that.template = that.partials[value];
        debugger;
        scope.$broadcast("REFRESH");
      }
    });
  }

  public static Factory(): angular.IDirectiveFactory {
    var directive = () => {
      return new CioTemplateLoader();
    };

    return directive;
  }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

你想要做的是动态编译html模板并渲染它们,对吧?如果是,则此问题可能会标记为重复,例如Compiling dynamic HTML strings from database