javascript - 动态注入(inject)指令

标签 javascript angularjs angularjs-directive

我需要 22 种不同类型的方式来展示某种类型的模型。我不想让我的 html 包含大量 if 语句和我的范围,而是想为每种类型创建一个指令。我根据 map 的类型从 map 中获取指令。功能如下。

$scope.getDirective = function (item) {
    var templateDirective = getDirective(item.type);
    var dir = '<' +  templateDirective + ' listId="' + $stateParams.listId + ' item="item">'
    return dir
  }

getDirective 是我正在使用的 map 。它工作得很好。

模板如下所示:

<div ng-repeat="item in templates | orderBy: sortOrder">
  <div ng-bind-html="getDirective(item)"></div>      
</div>

我遇到的第一个问题是,当将字符串放在一起时,字符串看起来像这样

"<temp-ratings listId="1" item="item">"

我正在使用的 map 工厂。

.factory('getDirective', [function () {
    var templates = {
      0: "temp-check",
      1: "temp-title",
      2: "temp-ratings",
      3: "temp-ratings1_10",
      4: "temp-short",
      5: "temp-long",
      6: "temp-log",
      8: "temp-yes-no",
      9: "temp-signature",
      10: "temp-text",
      11: "temp-multiple",
      12: "temp-employee",
      13: "temp-form",
      14: "temp-calculated",
      15: "temp-date",
      16: "temp-time",
      17: "temp-date_time",
      20: "temp-qr",
      21: "temp-barcode",
      22: "temp-photo",
      23: "temp-video"
    }

    return function (tempType) {
      return templates[tempType]
    }
  }])

另一个问题是当我检查元素时。它甚至没有尝试将其注入(inject)到 html 中。有人看到我做错了什么吗?

最佳答案

您可以编写自定义指令来动态编译其他指令,如下所示:

.directive('tempDynamic', function ($compile, getDirective) {
  return {
    scope: {
      item: '=tempDynamic'
    },
    link: function (scope, element, attrs) {
      var templateDirective = getDirective(scope.item.type);
      var html = '<' +  templateDirective + ' item="item">';
      var childElement = $compile(html)(scope);
      element.append(childElement);
    }
  }
});

并像这样使用它:

<div ng-repeat="item in templates" temp-dynamic="item"></div>

Plunker 示例: http://plnkr.co/edit/r5GNjklVpdbn2ADs7oSf?p=preview

希望这有帮助。

关于javascript - 动态注入(inject)指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25333987/

相关文章:

javascript - javascript执行上下文中的形参列表是什么?

angularjs - 如何处理来自$ sce.trustAsResourceUrl的错误

javascript - 404 仅在第一张图像的 ionic /Angular 中的 ng-repeat 上找不到图像

javascript - 为什么 splice 在 angular js 中不能正常工作

javascript - 从元素操纵光标位置

javascript - gmaps.js 使用 native Google Maps API v3 函数

javascript - 拉斐尔 JS : How to get Raphael element from Dom object(Element. 节点)?

javascript - 服务返回的值未在 angularjs 中的 Controller 变量中更新

javascript - AngularJS 如何创建具有 HTML 内容的指令?

javascript - 带有自定义模板的 AngularJS 指令