在重复动态添加伪指令(dynamically adding directives in ng-rep

2019-09-01 07:05发布

我试图在NG-重复但输出不被解释为指令动态添加不同的指令。

我已经在这里添加了一个简单的例子: http://plnkr.co/edit/6pREpoqvmcnJJWzhZZKq

控制器:

$scope.colors = [{name:"red"}, {name: "blue"}, {name:"yellow"}]; 

指示:

app.directive("red", function () {
    return {
        restrict: 'C',
        template: "RED directive"
    }
});

HTML:

<ul>
  <li ng-repeat="color in colors">
    <span class="{{color.name}}"></span>
  </li>
</ul>

如何使角拿起指定指令class是通过NG-重复输出?

Answer 1:

我知道这是一个老问题,但谷歌把我带到这里,我不喜欢这里的答案......他们似乎的东西,应该是简单非常复杂。 所以我创造了这个指令:

*****新内容*****

我因为做这个指令更通用,支持解析(典型的角度值)“属性”属性。

/**
 * Author: Eric Ferreira <http://stackoverflow.com/users/2954747/eric-ferreira> ©2016
 *
 * This directive takes an attribute object or string and adds it to the element
 *   before compilation is done. It doesn't remove any attributes, so all
 *   pre-added attributes will remain.
 *
 * @param {Object<String, String>?} attributes - object of attributes and values
 */
.directive('attributes', function attributesDirective($compile, $parse) {
    'use strict';

    return {
        priority: 999,
        terminal: true,
        restrict: 'A',
        compile: function attributesCompile() {
            return function attributesLink($scope, element, attributes) {
                function parseAttr(key, value) {
                    function convertToDashes(match) {
                        return match[0] + '-' + match[1].toLowerCase();
                    }

                    attributes.$set(key.replace(/([a-z][A-Z])/g, convertToDashes), value !== undefined && value !== null ? value : '');
                }

                var passedAttributes = $parse(attributes.attributes)($scope);

                if (passedAttributes !== null && passedAttributes !== undefined) {
                    if (typeof passedAttributes === 'object') {
                        for (var subkey in passedAttributes) {
                            parseAttr(subkey, passedAttributes[subkey]);
                        }
                    } else if (typeof passedAttributes === 'string') {
                        parseAttr(passedAttributes, null);
                    }
                }

                $compile(element, null, 999)($scope);
            };
        }
    };
});

对于OP的使用情况下,你可以这样做:

<li ng-repeat="color in colors">
    <span attributes="{'class': color.name}"></span>
</li>

或者使用它作为一个属性指令:

<li ng-repeat="color in colors">
    <span attributes="color.name"></span>
</li>

***** END新内容******

/**
 * Author: Eric Ferreira <http://stackoverflow.com/users/2954747/eric-ferreira> ©2015
 *
 * This directive will simply take a string directive name and do a simple compilation.
 * For anything more complex, more work is needed.
 */
angular.module('attributes', [])

.directive('directive', function($compile, $interpolate) {
    return {
        template: '',
        link: function($scope, element, attributes) {
            element.append($compile('<div ' + attributes.directive + '></div>')($scope));
        }
    };
})

;

对于这一问题的具体情况下,可以只改写指令一下,以便它通过类的指令适用于跨度,像这样:

angular.module('attributes', [])

.directive('directive', function($compile, $interpolate) {
    return {
        template: '',
        link: function($scope, element, attributes) {
            element.replaceWith($compile('<span class=\"' + attributes.directive + '\"></span>')($scope));
        }
    };
})

;

然后你可以使用这个在任何地方,并选择通过动态名称的指令。 使用它像这样:

<li ng-repeat="color in colors">
    <span directive="{{color.name}}"></span>
</li>

我特意保留了这个指令简单明了。 你可能(也可能会)必须改写它来满足您的需求。



Answer 2:

我面临着同样的问题,在我的项目之一,你可以看到我是如何解决这个问题的jsfiddle

HTML:

<div class="page-wrapper" ng-controller="mainCtrl">
  <div class="page">
    <h3>Page</h3>
    <ul>
        <li ng-repeat="widget in widgets"><div proxy="widget" proxy-value="{{widget}}"></div></li>
    </ul>
</div>

JS:

var app = angular.module('app',[]);
app.controller('mainCtrl', ['$scope', '$q', 'widgetAPI', function($scope, $q, widgetAPI) {
$scope.widgets = [];
widgetAPI.get().then(
    function(data) {
        $scope.widgets = data;
    },
    function(err) {
        console.log("error", err);
    }
);}])

.service('widgetAPI', ['$q', function($q) {
var api = {};
api.get = function() {
    //here will be $http in real app
    return $q.when(
        [
            {
                component: 'wgtitle',
                title: "Hello world",
                color: '#DB1F1F',
                backgroundColor: '#c1c1c1',
                fontSize: '32px'
            },
            {
                component: 'wgimage',
                src: "http://cs425622.vk.me/v425622209/79c5/JgEUtAic8QA.jpg",
                width: '100px'
            },
             {
                component: 'wgimage',
                src: "http://cs425622.vk.me/v425622209/79cf/S5F71ZMh8d0.jpg",
                width: '400px'
            }

        ]
    );
};
return api;}])

.directive('proxy', ['$parse', '$injector', '$compile', function ($parse, $injector, $compile) {
return {
    replace: true,
    link: function (scope, element, attrs) {
        var nameGetter = $parse(attrs.proxy);
        var name = nameGetter(scope);
        var value = undefined;
        if (attrs.proxyValue) {
          var valueGetter = $parse(attrs.proxyValue);
          value = valueGetter(scope);
        }

        var directive = $injector.get(name.component + 'Directive')[0];
        if (value !== undefined) {
            attrs[name.component] = value;
        }
        var a = $compile(directive.template)(scope);
        element.replaceWith(a);
    }
}}])

.directive('wgtitle', function() {
return {
    restrict: 'A',
    scope: true,
    replace: true,
    template: '<h1 style="color:{{widget.color}}; font-size:{{widget.fontSize}}; background:{{widget.backgroundColor}}" >{{widget.title}}</h1>',
    link: function(scope, element, attrs) {

    }
}})

.directive('wgimage', function() {
return {
    restrict: 'A',
    scope: true,
    replace: true,
    template: '<img style="width:{{widget.width}}" src="{{widget.src}}"/>',
    link: function(scope, element, attrs) {

    }
}});

我希望这将有用。



Answer 3:

我不认为你可以只分配指令作为类名称-您将需要通过运行这个$compile一次,这将是标题下向递归错误的路径。

一个可能的解决方案是在概述: AngularJS -如何有一个动态的子指令一个指令

它是否适合你的使用情况,您可以使用模板来代替:

<div ng-repeat='template in inner' ng-include='template'></div>


文章来源: dynamically adding directives in ng-repeat