当前位置: 首页 > 面试题库 >

在ng-repeat中动态添加指令

柳仲卿
2023-03-14
问题内容

我正在尝试在ng-repeat中html" target="_blank">动态添加不同的指令,但是输出没有被解释为指令。

我在这里添加了一个简单的示例: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-repeat 使角度拾取在中指定的指令?


问题答案:

我知道这是一个老问题,但是google将我带到了这里,但我不喜欢这里的答案。所以我创建了这个指令:

*新内容***

从那以后,我使该指令变得更加通用,支持已解析的(典型的角度值)“ attributes”属性。

/**
 * 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>

*结束新内容****

/**
 * 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>

我故意使该指令简单明了。您可能(并且可能会)不得不重新命名以适应您的需求。



 类似资料:
  • 问题内容: 我花了一段时间试图找到一个优雅的解决方案,而我却找到了一个“可行”的解决方案,它感觉不是最简单或正确的做事方式。 所以,我的问题是…如何动态加载指令!在某些情况下,以下是我希望我能摆脱它的方式!除了模板加载之外,我没有包含路由或其他任何内容,而是为下面的控制器分配了ng- controller。 app.js template.html 任何人都可以提供的建议将不胜感激,如果我做任何明

  • 问题内容: 我正在尝试创建一条指令,该指令允许将元素定义为可点击或不可点击,并且将被定义为: 我希望生成的HTML是: 我的指令实现如下所示: 我可以看到,添加新属性后,Angular不了解,因此不会触发。我尝试在设置属性后添加一个,但它会导致无限的链接/编译循环。 我知道我可以只检查函数中的值是否为,但是我很好奇如何动态添加事件来执行此操作,因为我可能需要使用多个其他指令来执行此操作,而我不想这

  • 问题内容: 我正在尝试根据当前项目动态显示ng-repeat指令中的多个模板之一。 我的JSON数据如下所示: 我的目标是动态渲染数据树,每个组包含多个部分。这些组都将具有相同的模板,但是每个部分都应基于名称字段具有自己的模板。 假设顶层HTML是: 理想情况下,每个部分还需要具有自己的范围数据和与其关联的控制器。我很幸运用Knockout构建了这种类型的系统,但是我想了解Angular的做事方式

  • 问题内容: 我正在做的事情非常精简,可以解决问题。 我有一个简单的。每当您单击一个元素时,它都会添加另一个元素。但是,需要先对其进行编译才能正确呈现。 我的研究使我走向了。但是所有示例都使用了一个复杂的结构,我真的不知道如何在这里应用它。 小提琴在这里:http : //jsfiddle.net/paulocoelho/fBjbP/1/ JS在这里: Josh David Miller的解决方案:

  • 问题内容: 是否可以根据条件向标签添加内容?像在此示例中一样,当我只想在第一次迭代中添加时(仅用于的第一个元素)? 问题答案: 是的,在这种情况下,AngularJS具有两个指令: 可以使用ng-show / ng-hide指令族基于评估表达式的结果来隐藏(通过使用显示CSS规则)DOM 3的一部分。 如果我们想有条件地物理删除/添加DOM的一部分,那么ng-switch指令家族(ng-switc

  • 问题内容: 我想在内容更改时创建具有自定义行为的列表。我尝试为此创建一个指令,但是我对如何将ng-transclude与ng- repeat指令结合起来感到迷茫。有人可以让我走上正轨吗? HTML: Javascript: 我已经在这里工作了一部分 编辑: 条件: 该项目的模板必须在视图中定义,而不是在指令中定义,并且必须有权访问子作用域中的项目属性。理想情况下,我想像在ng-repeat指令中那