【问题标题】:Why my directives don't work in Plunker?为什么我的指令在 Plunker 中不起作用?
【发布时间】:2015-06-11 19:59:56
【问题描述】:

我打算使用 Plunker 来帮助我测试一个指令,但首先我只是想创建一个来测试 plunker 是否工作,所以我输入了一些示例代码。你猜怎么着,基本指令不起作用,我不知道为什么。

我的指令:

app.directive('attributeDirective', function() {
  return {
    restrict: 'A',
    link: function(scope, iElement, iAttrs) {

      iElement.bind('click', function() {
        console.log('clicked attributeDirective');
      });
      iElement.bind('mouseover', function() {
        iElement.css('cursor', 'pointer');
      });
    }
  };
});

app.directive('elementDirective', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<h2>this is elementDirective</h2>',
    link: function(scope, iElement, iAttrs) {

      iElement.bind('click', function() {
        console.log('clicked elementDirective');
      });
      iElement.bind('mouseover', function() {
        iElement.css('cursor', 'pointer');
      });
    }
  };
});

我的html:

<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>

<h2 attributeDirective>Here is my attribute directive</h2>

<elementDirective></elementDirective>

</body>

http://plnkr.co/edit/H9vPhV

【问题讨论】:

    标签: angularjs angularjs-directive plunker


    【解决方案1】:

    html 中调用指令时,您应该像这样替换指令名称中的camelcase

    &lt;element-directive&gt;&lt;/element-directive&gt; 而不是原来的样子,

    &lt;elementDirective&gt;&lt;/elementDirective&gt;

    就像你做的那样。

    希望对你有帮助!!!

    PLUNKER

    see through the custom directives here

    【讨论】:

    【解决方案2】:

    你应该使用

    <h2 attribute-directive>Here is my attribute directive</h2>
    

    http://plnkr.co/edit/2aGGDRw6SdYNc1joSVI1?p=preview

    【讨论】:

      【解决方案3】:

      常见问题 - 您不能在 HTML 元素声明中使用驼峰式大小写。

      试试&lt;element-directive&gt;&lt;/element-directive&gt;

      【讨论】:

        【解决方案4】:

        在指令中使用restrict: 'A' 来引用属性。 在指令中使用restrict: 'E' 来引用元素。

        找到plunkr:“http://plnkr.co/edit/b1cf6l?p=preview

        同时调用你的指令:

        <h2 attribute-directive>Here is my attribute directive</h2>   
        <element-directive></element-directive>
        

        【讨论】:

          猜你喜欢
          • 2020-12-21
          • 2016-10-03
          • 2011-10-22
          • 1970-01-01
          • 2020-03-27
          • 2019-05-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多