javascript - 从父指令或 Controller 中的指令名称数组呈现 AngularJS 指令

标签 javascript angularjs

我正在尝试根据指令名称的配置数组动态呈现指令。这可能有 Angular 吗?我还希望这些呈现的指令存在于单个父 dom 元素中,而不是每个都获得一个新的包装器(就像使用 ng-repeat 一样)

http://jsfiddle.net/7Waxv/

var myApp = angular.module('myApp', []);

myApp.directive('one', function() {
    return {
        restrict: 'A',
        template: '<div>Directive one</div>'
    }
});

myApp.directive('two', function() {
    return {
        restrict: 'A',
        template: '<div>Directive two</div>'
    }
});

function MyCtrl($scope) {
    $scope.directives = ['one', 'two'];
}

<div ng-controller="MyCtrl">
    <div ng-repeat="directive in directives">
        <div {{directive}}></div>
    </div>
</div>

编辑: 自从发布这个,我也尝试过:

.directive('parentDirective', function () {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, element) {
      scope.directives = ['one', 'two'];
      for (var i = 0; i < scope.directives.length; i++) { 
        element.prepend('<div ' + scope.directives[i] + '></div>')
      }
    }
  };
});

<div parent-directive></div>

有了这个,来自前置指令的模板就不会被渲染。

最佳答案

这是我想出的(花了很长时间)...尽管该解决方案非常通用,您可以随意修改 $scope.directives 数组,指令将动态生成。您还可以指向当前作用域中的任何特定属性以从中检索指令列表。

Demo link

app.js

var myApp = angular.module('myApp', []);

myApp.directive('one', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div>Directive one</div>'
    }
});

myApp.directive('two', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div>Directive two</div>'
    }
});

myApp.directive('dynamic', function ($compile, $parse) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, element, attr) {
      attr.$observe('dynamic', function(val) {
        element.html('');
        var directives = $parse(val)(scope);
        angular.forEach(directives, function(directive) {
          element.append($compile(directive)(scope));
        });
      });
    }
  };
});

function MyCtrl($scope) {
    $scope.directives = ['<one/>', '<two/>'];
    $scope.add = function(directive) {
        $scope.directives.push(directive);
    }
}

index.html

<div ng-controller="MyCtrl">
    <div dynamic="{{directives}}"></div>
    <button ng-click="add('<one/>')">Add One</button>
    <button ng-click="add('<two/>')">Add One</button>
</div>

关于javascript - 从父指令或 Controller 中的指令名称数组呈现 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18543298/

相关文章:

javascript - 在 # 符号后检测 url 更改

javascript - Fabric.JS 与 Node.JS - 导出为 PNG/JPEG

javascript - 对于 () 对于变量

javascript - 具有函数绑定(bind)的 Angular 指令范围评估 ('&' )

angularjs - 使用 ng-grid : binding issue? 进行服务器端过滤

javascript - 如何创建嵌套在 html 内容中的基础弹出窗口(模板)

angularjs - 是否可以从一个 $routeProvider 条件提供多个部分服务?

javascript - 在 Magento 产品页面上添加动态 JS 代码

javascript - 如何使用 Three.js 中的 "WebGLRenderer"绘制 Matter.js 对象?

javascript - UI-router 空参数导致导航到错误的路线