检查指令是否具有属性

Check if directive has an attribute

本文关键字:属性 是否 指令 检查      更新时间:2023-09-26

>我有以下代码

<my-directive></my-directive>

我想评估其中的以下特雷纳:

{{ $scope.my-option ? 'YES' : 'NO' }}

喜欢这个:

<my-directive my-option></my-directive>

我该怎么做?一旦我有了属性,它的评估结果应该为 true,对吧?我已经将属性与=符号绑定在一起。

您不应该在此处检查$scope.my-option,而应检查$scope.myOption

CamelCased 属性在 HTML 代码中只采用蛇形大小写;它们应该在所有剩余的 JavaScript 源代码中使用 camelCase 引用。

因此,您的 HTML 标记应该是这样的:

<my-directive my-option></my-directive>

但是你的AngularJS表达式将是:

{{ $scope.myOption ? 'YES' : 'NO' }}

甚至可能不需要$scope,什么会减少表达式

{{ myOption ? 'YES' : 'NO' }}

此外,如果您不想在 HTML 中显式添加检查作为观察程序,则可以使用指令的 link 函数来执行此操作。文档对此进行了更详细的解释。

在您的指令中,像以下代码片段一样使用它:

angular
    .module('myModule')
    .directive('myDirective', function() {
        return {
            restrict: 'A',
            scope: {
                myOption: '=?'
            },
            link: function(scope, element) {
                if (scope.myOption) {
                    // you have the attribute
                } else {
                    // you don't
                }
            }
        }
    });

如果您没有隔离范围(并且也适用于隔离范围),您可以直接检查 attrs:

angular
.module('myModule')
.directive('myDirective', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var option;
            if (attrs.hasOwnProperty('myOption')) {
                // if attr is plain string
                option = attrs.myOption;
                // or parse from a scope property
                option = $parse(attrs.myOption)(scope);
            }
        }
    }
});