有条件地将angular指令属性添加到元素

时间:2015-05-07 16:29:30

标签: angularjs angularjs-directive

是否有直接,简单的方法来执行以下操作 -

<div class="my-class" my-custom-directive="{{evaluate expression}}"></div>

除非表达式被评估为真,否则angular 不会添加指令?

编辑:

该指令必须是一个属性所以请,没有解决方案 ng-if restrict: 'E',{。} ng-class restrict: 'C'ng-attr的{​​{1}} - 不适用于自定义指令。

3 个答案:

答案 0 :(得分:5)

可以通过创建具有高优先级和terminal: true的指令来实现此目的。然后你可以摆弄元素属性(添加或删除它们),然后重新编译元素以使指令运行。

以下是插件示例:http://plnkr.co/edit/DemVGr?p=info

更改&#34;指令中的表达式 - 如果&#34;属性以保留/删除&#34;记录器&#34;指令。

如果属性的表达式的计算结果为false,那么它将被删除。

<div directive-if="{'logger': 'myValue == 1'}"
     logger="testValue">
    <p>"logger" directive exists? <strong>{{logger}}</strong></p>
</div>

这是指令实现。

通过一些小的调整,您可以将其交换为添加指令,而不是删除它们,如果这是您想要的。

/**
 * The "directiveIf" directive allows other directives
 * to be dynamically removed from this element.
 *
 * Any number of directives can be controlled with the object
 * passed in the "directive-if" attribute on this element:
 *
 *    {'attributeName': 'expression'[, 'attribute': 'expression']}
 * 
 * If `expression` evaluates to `false` then `attributeName`
 * will be removed from this element.
 *
 * Usage:
 *
 *         <any directive-if="{'myDirective': 'expression'}"
 *                    my-directive>
 *         </any>
 *
 */
directive('directiveIf', ['$compile', function($compile) {

    // Error handling.
    var compileGuard = 0;
    // End of error handling.

    return {

        // Set a high priority so we run before other directives.
        priority: 100,
        // Set terminal to true to stop other directives from running.
        terminal: true,

        compile: function() {
            return {
                pre: function(scope, element, attr) {

                    // Error handling.
                    // 
                    // Make sure we don't go into an infinite 
                    // compile loop if something goes wrong.
                    compileGuard++;
                    if (compileGuard >= 10) {
                        console.log('directiveIf: infinite compile loop!');
                        return;
                    }
                    // End of error handling.


                    // Get the set of directives to apply.
                    var directives = scope.$eval(attr.directiveIf);
                    angular.forEach(directives, function(expr, directive) {
                        // Evaluate each directive expression and remove
                        // the directive attribute if the expression evaluates
                        // to `false`.
                        var result = scope.$eval(expr);
                        if (result === false) {
                            // Set the attribute to `null` to remove the attribute.
                            // 
                            // See: https://docs.angularjs.org/api/ng/type/$compile.directive.Attributes#$set
                            attr.$set('logger', null)
                        }
                    });


                    // Remove our own directive before compiling
                    // to avoid infinite compile loops.
                    attr.$set('directiveIf', null);

                    // Recompile the element so the remaining directives
                    // can be invoked.
                    var result = $compile(element)(scope);


                    // Error handling.
                    // 
                    // Reset the compileGuard after compilation
                    // (otherwise we can't use this directive multiple times).
                    // 
                    // It should be safe to reset here because we will
                    // only reach this code *after* the `$compile()`
                    // call above has returned.
                    compileGuard = 0;

                }
            };

        }
    };
}]);

答案 1 :(得分:2)

@Sly_cardinal是对的,使用了他的代码,但不得不做一些调整:

(function () {

angular.module('MyModule').directive('directiveIf', function ($compile) {

    // Error handling.
    var compileGuard = 0;
    // End of error handling.

    return {

        // Set a high priority so we run before other directives.
        priority: 100,
        // Set terminal to true to stop other directives from running.
        terminal: true,

        compile: function() {
            return {
                pre: function(scope, element, attr) {

                    // Error handling.
                    // Make sure we don't go into an infinite
                    // compile loop if something goes wrong.
                    compileGuard++;
                    if (compileGuard >= 10) {
                        console.log('directiveIf: infinite compile loop!');
                        return;
                    }


                    // Get the set of directives to apply.
                    var directives = scope.$eval(attr.directiveIf);

                    for (var key in directives) {
                        if (directives.hasOwnProperty(key)) {

                            // if the direcitve expression is truthy
                            if (directives[key]) {
                                attr.$set(key, true);
                            } else {
                                attr.$set(key, null);
                            }
                        }
                    }

                    // Remove our own directive before compiling
                    // to avoid infinite compile loops.
                    attr.$set('directiveIf', null);

                    // Recompile the element so the remaining directives
                    // can be invoked.
                    var result = $compile(element)(scope);


                    // Error handling.
                    //
                    // Reset the compileGuard after compilation
                    // (otherwise we can't use this directive multiple times).
                    //
                    // It should be safe to reset here because we will
                    // only reach this code *after* the `$compile()`
                    // call above has returned.
                    compileGuard = 0;

                }
            };

        }
    };
});

})();

答案 2 :(得分:0)

另一种方法是创建两个版本的代码 - 一个在需要指令时,另一个在不需要时。并使用ng-if / ng-show显示一个或另一个。可以将重复的代码移动到模板中,这些代码可以包含在内。