在 Gridster 中动态添加指令 AngularJS

Dynamically add a directive in AngularJS within Gridster

我刚开始使用AngularJS,但我发现了一个我无法解决的小问题,希望你们能帮帮我。

我已经导入了 AngularJS Gridster,这是一种向您的网页添加动态网格的简单方法。现在一切正常,元素从数据库中成功加载并导入到 Gridster 中,但现在我想做以下事情。在从数据库中检索到的 JSON 中,还有一个名为 "directive" 的属性。现在,当所有内容都加载完毕后,我想在每个 Gridster 元素中添加从数据库返回的指令。

<ul>
    <li gridster-item="item" ng-repeat="item in gridsterItems">
        {{ item.directive }} // Returns <clock-widget></clock-widget> and print it to the screen, but it dont run the directive and doesn't display.
    </li>
</ul>

现在它 returns 正确的值并在屏幕上显示字符串,但我想 运行 它指令 clockWidget。

app.directive('clockWidget', function() {
return {
    replace: true,
    template: 'Yups, I am the clockwidget',
};
});

在互联网上我读到了有关 $compile 的内容,但我找不到。希望各位大神帮帮我

谢谢!

是的,您需要使用 $compile。参见 documentation

jsfiddle.

上的实例

angular.module('ExampleApp', [])
  .controller('ExampleController', function($scope) {
    $scope.directives = ["<directive-one></directive-one>", "<directive-two val='inputVal'></directive-two>"];
  })
  .directive('compileDirective', function($compile) {
    return {
      restrict: "E",
      replace: true,
      link: function(scope, element, attr) {
        scope.$watch(function() {
          return attr.directive;
        }, function(val) {
          element.html("");
          if (val) {
            var directive = $compile(angular.element(val))(scope);
            element.append(directive);
          }
        });
      }
    };
  })
//Directives for example
  .directive('directiveOne', function($compile) {
    return {
      replace: true,
      template: "<div>i'm directive one</div>"
    };
  })
  .directive('directiveTwo', function($compile) {
    return {
      replace: true,
      scope:{val:"="},
      template: "<div>i'm directive two with val={{val}}</div>"
    };
  })
  .directive('directiveThree', function($compile) {
    return {
      replace: true,
      scope:{val:"="},
      template: "<div>i'm directive three</div>"
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">
    <select ng-model="selectDirective" ng-options="dir for dir in directives">
    </select>
    <input ng-model="inputVal">
    <compile-directive directive="{{selectDirective}}"></compile-directive>
    <compile-directive directive="<directive-three></directive-three>"></compile-directive>
  </div>
</div>