简体   繁体   English

您可以观看触发指令的属性吗?

[英]Can you watch the attribute which triggered the directive?

Is it possible to watch the attribute which triggered the directive? 是否有可能观看触发指令的属性?

export function minDirective(): ng.IDirective {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: (scope, elem, attr, ctrl) => {
      scope.$watch(<name of the attribute>, () => {
        // Do something
      });
    }
  };
}

I'd like to listen to bb-civic-registration-number-format attribute the example below, except I have no idea it's named that way by the programmer reusing my directive: 我想听下面的示例中的bb-civic-registration-number-format属性,除了我不知道程序员重用我的指令以这种方式命名它:

在此处输入图片说明

I'm trying to create a validation directive which would take an arbitrary expression and use it for validation. 我正在尝试创建一个验证指令,该指令将采用任意表达式并将其用于验证。 A typical example is ngMin and ngMax except I'd like to implement similar functionality for an arbitrary input type: 一个典型的示例是ngMinngMax,但我想为任意输入类型实现类似的功能:

<input type="number" ng-model="someModel" />
<input type="text" myprefix-max="someModel*0.5" />

If I understand question properly you can use the attribute value and [] notation. 如果我正确理解问题,则可以使用属性值和[]表示法。

<element my-directive scope-var="controllerScopePropertyName"></element >

JS JS

export function myDirective(): ng.IDirective {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: (scope, elem, attr, ctrl) => {

      // using ES5 syntax
      scope.$watch(function(){
          return scope[attr.scopeVar];
      }, function(newVal,oldVal){
         // do something
      });
    }
  };
}

Alternatively just set up isolated scope and bind directly to the controller 或者,只需设置隔离的作用域并直接绑定到控制器

You can actually get the name of your directive in the compile function, which should give you the ability to look up the value by comparing it to the attribute collection. 实际上,您可以在编译函数中获得指令的名称,这应该使您能够通过将其与属性集合进行比较来查找值。

compile: function (elem, attrs) {
    console.log(this.name);
}

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

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