具有bool属性的角度指令传递字符串而不是bool

Angular directive with bool attribute passing string instead of bool

本文关键字:bool 字符串 指令 属性 具有      更新时间:2023-10-21

我正试图创建一个指令,该指令将禁用容器内的所有输入元素,但我在属性方面遇到了问题。这是我收到的指令

指令

angular.module('common')
    .directive('bdDisabled', [function () {
            return {
                restrict: 'A',
                scope: {
                    bdDisabled: '='
                },
                link: function (scope, element, attrs) {
                    attrs.$observe('bdDisabled', function(newValue, oldValue) {
                        if (newValue !== oldValue) {
                            if (newValue) {
                                element.find('input, select, button, submit, textarea').prop('disabled', 'disabled');
                            } else {
                                element.find('input, select, button, submit, textarea').removeProp('disabled');
                            }
                        }
                    });
                }
            };
        }
    ]);

这就是我想要使用它的方式:

<div class="cg-content cg-shadow" bd-disabled="isLoading">

问题是属性值是字符串isLoading,而不是值。

如果我用大括号把它包起来,它就会坏掉,我会在控制台中得到一个错误。如果我用大括号括起来,并将作用域改为"@"而不是"=",它就可以工作了。但它发送字符串"true"或"false",而不是布尔值。

我哪里错了?

正如我在评论中所建议的,我会将attrs.$observe切换为scope.$watch。根据个人喜好,我也会使用函数表达式而不是字符串,因为例如,如果你正在使用(或将要使用)typescript,如果属性发生变化,你会收到通知,其中字符串可能会保持原样:

scope.$watch(function () {
      return scope.bdDisabled;
      }, 
      function (newVal, oldVal) {
          ...
      }
);

您不必将observe与'='一起使用。有关详细信息,请参阅下面的链接,我相信它比文档健壮得多。

'@';和'=';在AngularJS的指令范围内?

就您的代码而言,我会仔细检查isLoading变量,以确保它是布尔值。

当您将范围定义从"="更改为"@"时,您只想将作为字符串传递,而不是双向绑定模式。当然,你可以把它转换成真的,比如:

var myBool = Boolean("false"); // === true

var myBool = Boolean("true"); // === true

但要小心,因为任何字符串都可以被视为true,比如:

var myBool = Boolean("foo"); // === true