【问题标题】:Dynamically add a directive in AngularJS within Gridster在 Gridster 中的 AngularJS 中动态添加指令
【发布时间】:2016-04-06 10:52:15
【问题描述】:

我刚开始使用AngularJS,但发现了一个我无法找到的小问题,希望各位大神能帮助我。

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

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

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

在互联网上我读到了一些关于 $compile 但我找不到的东西。希望各位大神能帮帮我。

谢谢!

【问题讨论】:

    标签: javascript angularjs gridster


    【解决方案1】:

    是的,您需要使用$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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 2017-03-23
      • 2013-12-18
      • 1970-01-01
      • 2018-01-06
      相关资源
      最近更新 更多