【问题标题】:AngularJS directive to add other directives not functionalAngularJS指令添加其他指令不起作用
【发布时间】:2015-06-24 14:57:27
【问题描述】:

我正在尝试构建一个将表单组添加到特定 div 的指令。我试图通过将指令绑定到我的html中的按钮来做到这一点。我的应用程序非常简单,因为这就是我目前要做的所有事情。类似于this fiddle 无论如何,我的应用程序启动良好,并且包含家庭控制器。此外,在包含我的指令时,我得到了 200 个状态代码,并且我的代码没有抛出任何错误。这是我的html:

  <form id="addFields">
<div class="row">
  <div class="col-xs-4">
  </div>
  <div class="col-xs-4 text-center">
    <div addInputFieldsButton></div>
    <input id="fieldName" placeholder="Enter field name:"></input>
    <button id="addFieldBtn" addInputFields><span class="glyphicon glyphicon-plus"></span></button>
  </div>
  <div class="col-xs-4">
  </div>
</div>
</form>
<div id="reviewFields">
</div>

请注意,我正在尝试添加应该添加输入字段的按钮,并且只是将添加输入字段的指令绑定到现有按钮作为属性。都不工作。

addInputFields 指令:

(function () {
  angular.module('reviewModule')
    .directive('addInputFields', addInputFields);

  addInputFields.$inject = ['$log'];
  function addInputFields ($log) {
    return function (scope, element, attr) {
      $log.debug('binding click event to add review button now.');
      element.bind('click', function ($compile) {
        $log.debug('button bound.');
        angular.element(document.getElementById('reviewFields')).append($compile("<button>YOU MADE A BUTTON, COOL BRO</button>")(scope));
      });
    }
  }
})()

以及我尝试添加具有上述绑定的按钮的指令:

(function () {
  angular.module('reviewModule')
    .directive('addInputFieldsButton', addInputFieldsButton);

  addInputFieldsButton.$inject = ['$log'];
  function addInputFieldsButton ($log) {
    return {
      restrict : 'E',
      template : '<input id="fieldName" placeholder="Enter field name:"></input>\
        <button id="addFieldBtn" addInputFields><span class="glyphicon glyphicon-plus"></span></button>'
    };
  };
})()

我几乎完全复制了小提琴,并且真的不知道为什么在尝试使用这些指令中的任何一个时都没有发生任何事情。如果我的错误很明显,请原谅我,我对 AngularJS 还是很陌生。

【问题讨论】:

    标签: javascript html angularjs dom angularjs-directive


    【解决方案1】:

    我相信您的第二个指令在 UI 上没有正确定义,它应该是 - 用小写分隔 add-input-fields 而不是 addInputFields。

    代码

    (function () {
      angular.module('reviewModule')
        .directive('addInputFieldsButton', addInputFieldsButton);
    
      addInputFieldsButton.$inject = ['$log'];
      function addInputFieldsButton ($log) {
        return {
          restrict : 'E',
          template : '<input id="fieldName" placeholder="Enter field name:"></input>\
            <button id="addFieldBtn" add-input-fields><span class="glyphicon glyphicon-plus"></span></button>'
                                    //^^^^^^^^^^^^^^^here is change
        };
      };
    })()
    

    【讨论】:

    • 非常感谢您快速正确的回答!我刚刚用 PHP api 项目开发了一个 jQuery,所以我对 angularJS 的怪癖有点生疏。忘记了在 html 中指令名称的变化。
    猜你喜欢
    • 1970-01-01
    • 2014-04-30
    • 2015-06-20
    • 1970-01-01
    • 2018-09-07
    • 2017-03-23
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多