javascript - ng-repeat 内的指令列表

标签 javascript angularjs angularjs-directive angularjs-ng-repeat

我正在处理一个由 5 个指令组成的页面,例如:

<directive-one></directive-one>
<directive-two></directive-two>
<directive-three></directive-three>
<directive-four></directive-four>
<directive-five></directive-five>

我希望能够根据需要重新排序,以便用户可以控制其页面的外观。我能想到的唯一方法是将它们放入 ng-repeat 中:

$scope.directiveOrder = [{
    name: "directive-one",
    html: $sce.trustAsHtml('<directive-one></directive-one>'),
    order: 1
}, ...

HTML:

<div ng-repeat="directive in directiveOrder" ng-bind-html="directive.html">
    {{directive.html}}
</div>

这将为我提供正确的标签,但它们不会被 Angular 处理为指令。有办法解决这个问题吗?我假设这与 $sce 没有处理它有关,但我可能偏离了?

最佳答案

尝试创建一个新指令并使用 $compile 呈现每个指令:

https://jsfiddle.net/HB7LU/18670/ http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx

HTML

<div ng-controller="MyCtrl">
    <button ng-click="reOrder()">Re-Order</button>
    <div ng-repeat="d in directives">
        <render template="d.name"></render>
    </div>
</div>

JS

var myApp = angular.module('myApp',[])
.directive('directiveOne', function() {
    return {
        restrict: 'E',
        scope: {},
        template: '<h1>{{obj.title}}</h1>',
        controller: function ($scope) {
            $scope.obj = {title: 'Directive One'};
        }
    }
})
.directive('directiveTwo', function() {
    return {
        restrict: 'E',
        scope: {},
        template: '<h1>{{obj.title}}</h1>',
        controller: function ($scope) {
            $scope.obj = {title: 'Directive Two'};
        }
    }
})
.directive("render", function($compile){
    return {
        restrict: 'E',
        scope: {
            template: '='
        },
        link: function(scope, element){
            var template = '<' + scope.template + '></' + scope.template + '>';
            element.append($compile(template)(scope));
        }
    }
})
.controller('MyCtrl', function($scope, $compile) {
    $scope.directives = [{
        name: 'directive-one'
    }, {
        name: 'directive-two'
    }];
    $scope.reOrder = function () {
        $scope.directives.push($scope.directives.shift());
        console.log($scope.directives);
    };
});

关于javascript - ng-repeat 内的指令列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33158780/

相关文章:

angularjs $q & $http 关于 promise

angularjs - 如何在 ngtable( Angular 插件)中设置动态数据标题

javascript - 在 Angularjs 中访问模板内的属性值

angularjs - Angular ui 选项卡,每个选项卡都有单独的 Controller

javascript - angularjs 范围变量未在指令外部更新

javascript - 如何在按钮点击jquery中设置2个条件

javascript - 从 child 更改 parent 的状态并在另一个 child react native 中使用它

javascript - 在一次字符串遍历中将大文本中的 **title** 转换为 <h1>title</h1> 的最佳方法是什么?

Javascript:JSON.stringify 未按预期工作

javascript - angularjs中如何实现基类和派生类的概念?