javascript - AngularJS - 在指令中绑定(bind)多个类

标签 javascript angularjs angularjs-directive

我正在使用 Waves 插件,我想在 3 个不同的类上使用它。

在 jQuery 中我的代码是这样的

Waves.attach('.button', ['waves-button', 'waves-float']);
Waves.init();

在 Angular 中,我已经将其转换为指令

.directive('waves', function(){
        return {
            restrict: 'A',
            link: function(scope, element) {
                Waves.attach('.btn', ['waves-button', 'waves-float']);
                Waves.init();
            }
        }
    })

我有很多带有上述类的元素,在所有这些元素中,我必须使用一个额外的属性来使其工作 data-waves

为避免这种情况,我将指令限制为类,但我只能绑定(bind)一个类。

.directive('btn', function(){
      return {
          restrict: 'C',
          ...

当指令仅限于类时,如何将多个类绑定(bind)到单个指令?我期待一些像

.directive(['class1', 'class2', 'class3'], function(){
      return {
         restrict: 'C',

最佳答案

我认为您必须创建新指令但共享工厂函数。

function mySharedDirectiveFactory () {
  return {
  // directive object
  };
}
angular.module('myModule')
.directive('class1', mySharedDirectiveFactory)
.directive('class2', mySharedDirectiveFactory)
.directive('class3', mySharedDirectiveFactory);

无论如何,我认为最好的办法是只创建一个指令并将其限制为一个元素或一个属性,这样您就只有一个定义。

关于javascript - AngularJS - 在指令中绑定(bind)多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30434641/

相关文章:

JavaScript 正则表达式 : Different results: Built pattern using string & using regexp "literal"?

javascript - 当我长按键盘上的某个键时事件输入错误页面

angularjs - 更改所选 ng-repeat 项的样式并删除其他项的样式

javascript - 指令 "link"不符合我的要求

javascript - 使用 AngularJS 动态内容加载 Owl Carousel 2

javascript - 将最大日期值设置为当前日期或从开始日期起 1 年

javascript - 正则表达式 : how to replace a string (as a variable) that has a digit in it?

javascript - 单页应用有多个css文件,如何在文件中划分css?

javascript - 告诉子指令在父指令完成 DOM 操作后执行操作?

javascript - 创建 Angular Directive(指令)以重用代码 - 创建 html 时解析错误