用于可扩展性的AngularJS动态指令

时间:2017-07-03 15:41:08

标签: angularjs angularjs-directive

我已经看过这个问题几次询问不同的原因询问;我认为这足以保证一个新问题。

我正在开发的应用程序通过插件架构支持可扩展性。后端(.NET)支持添加扩展后端功能的新插件程序集。通常,它们也包含JS / HTML /等。预先加载在前端的资源,以允许最终用户使用扩展功能。

我目前的设计选择是插件包含一个JS资源,它将指令/组件注册到AngularJS应用程序模块。 问题动态(有条件地)添加呈现这些指令。

假设一个插件扩展了给定事物支持的数据源(报告或其他)。最终用户从下拉列表中选择一个插件源。这将要求最终用户选择其他特定于插件的设置。据我所知,将UI /功能细节封装到<foo-plugin-data-source />是最常用的选项。但是,我如何有条件地/以编程方式呈现该指令

我的搜索一直把我带到$compile,我可能会把它与它混在一起;但我很好奇是否有什么东西&#34;更清洁&#34;。

在中间容器指令中的东西:

var name = 'fooPluginDataSource';
var directive = $directiveLoader.load(name, { opts });
element.append(directive);

基于某些状态,以编程方式而不是声明方式加载指令的最理智的方式是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用指令来编译插件,使用受控数据,如下所示:

<plugin name="'my-plugin-directive'" options="options"></plugin>

下面的工作示例:

angular
  .module('myPluginModule', [])
  .directive('myPluginDirective', function($compile) {
    return {
      restrict: 'E',
      scope: {
        a: '=',
        b: '='
      },
      template: '<br>a: {{ a }}<br>b.c: {{b.c}}<br>b.d: {{b.d}}'
    };
  });

angular
  .module('app', ['myPluginModule'])
  .directive('plugin', function($compile) {
    return {
      restrict: 'E',
      scope: {
        name: '=',
        options: '='
      },
      link: function($scope, $element) {

        var attrs = Object.keys($scope.options)
          .map(function(opt) {
            return opt + '="options.' + opt + '"';
          }).join(' ');

        var template = '<' +
          $scope.name +
          (attrs !== '' ? ' ' + attrs : '') +
          '></' + $scope.name + '>';

console.log(template);

        var elemt = $compile(template)($scope);
        $element.append(elemt);
      }
    };
  })
<div ng-app="app" ng-init="options = {a:1, b: {c:2, d:3}}">
  <plugin name="'my-plugin-directive'" options="options"></plugin>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>