简体   繁体   English

如何限制自定义指令的可能属性值?

[英]How can I restrict the possible attribute values of a custom directive?

Currently I am trying: 目前,我正在尝试:

module.directive('myDirective', function() {
    return {
        scope: { foo: '@' },
        template: '{{foo}}',
        link: function(scope) {
            if (scope.foo != 'first' && scope.foo != 'second')
              throw new Error("Only values 'first' and 'second' allowed for attribute 'foo' of myDirective");
        }
    };
});

But is there a "more angular" way? 但是,有没有一种“更棱角分明”的方式?

When you have a set of values (like enums) that could be passed to the directive, you should make this set available to the controller as well as to the directive. 当您有一组可以传递给指令的值(例如枚举)时,您应该使该设置对控制器和指令均可用。

For example, if you can only pass certain colors, you should create a color constant and inject this constant in the controller as well as in the directive. 例如,如果您只能传递某些颜色,则应创建一个颜色常量,并将该常量注入控制器以及指令中。 From the controller you pass it to the directive and in the directive you check against the color constant collection. 从控制器将其传递给指令,然后在指令中检查颜色常量集合。

I don't think you can make the check itself easier, or more like the 'angular way'. 我认为您不能使检查本身更容易,或更像是“成角度的方式”。 You could however create a factory method that checks if the color is a valid color from the constant for example. 但是,您可以创建一种工厂方法,例如,从常量中检查颜色是否为有效颜色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM