【问题标题】:Edit in Place Directive with Button使用按钮编辑就地指令
【发布时间】:2013-10-31 20:10:50
【问题描述】:

我正在实现就地编辑功能,在用户单击按钮后,这些字段变得可编辑。这是两个指令:

按钮指令:

.directive('editbutton', function() {
   return {
       restrict: 'A',
       template: '<div ng-hide="editorEnabled>' +
          '<button class="btn btn-small" ng-click="enableEditor(item)">' +
             '<i class="icon-edit"></i>' +
          '</button>' +
        '</div>' +
    '<div ng-show="editorEnabled>' +
      '<button class="btn btn-small" ng-click="save(item)">' +
        '<i class="icon-ok"></i>' +
      '</button>' +
    '</div>',
link: function(scope, elm, attrs, ctrl) {
  console.log("butotn");

  scope.editorEnabled = false;

  scope.enableEditor = function(item){
    scope.editorEnabled = true;
  }

  scope.disableEditor = function(){
    scope.editorEnabled = false;
  }

  scope.save = function(){
    // edit client side and server side
    scope.disableEditor();
  }

}
};
});

对于文本就地编辑:

angular.module('solarquote.directives', []).directive('editfield', function() {
return {
restrict: 'A',
   //scope: { value:"=editfield", inherit:'@editorEnabled'},
   transclude: true,
   template: '<span ng-hide="editorEnabled" ng-transclude></span>' +   // viewable field
     '<span ng-show="editorEnabled"><input class="input-medium" ng-model="value"></span>', // editable field
   link: function(scope, elm, attrs, ctrl) {
       // nothing here
   }
};
})

还有 HTML:

    <tr ng-repeat="item in items">
  <td>
    <a href="" ng-click="filter_fund(item)">
      <span editfield="item.fields.name">{{ item.fields.name }}</span>
    </a>
  </td>

  <td>
    <span editfield="item.fields.address">{{ item.fields.address }}</span>
  </td>

  <td style="text-align:center" ng-show="editable_table"><span editbutton></span></td>

问题是,当我实现自己的范围以检索名称时,无法访问 editorEnabled 范围。我曾尝试使用 @ 和 = 来获取“继承”范围,但无法弄清楚如何。

目标是使用 =editfield 预填充输入字段。然后将 editorEnabled 范围与启用和禁用它的按钮共享。但是,该范围没有启用编辑器。

任何帮助将不胜感激。

【问题讨论】:

  • 查看本教程,了解从指令到指令通信的内容。还有其他与指令相关的教程,我发现它们非常有用。 egghead.io/video/rzMrBIVuxgM

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

有两个关键点可以让它发挥作用:

  1. 处理 isolated scope 指令 - 您必须通过所有必需的 通过属性数据。在您的示例中,它应该是 editfieldeditorEnabled。例如:

    <span editfield="item.fields.name" editor-enabled="editorEnabled">
    

    和 in 指令:

    scope: { value:"=editfield", editorEnabled: '='},
    
  2. 向指令传递数据时不要在属性名称中使用驼峰命名法

    这行不通

    <span editfield="user.name" editorEnabled="editorEnabled">
    

这是工作小提琴:http://jsfiddle.net/wLQH3/1/

您还可以签出angular-xeditable 库,它完全可以完成您的任务,而无需编写自己的自定义指令。

【讨论】:

    【解决方案2】:

    嗯。我不知道您是否需要为此编写自定义指令。

    如果我是你,我会在我的输入字段中添加 ng-disabled,类似于:

    <button ng-model="clicked"></button>
    <input ng-disabled="clicked"/>
    

    每当单击按钮时,以下内容将启用/禁用(使其可编辑/不可编辑)输入字段。

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2017-09-11
      相关资源
      最近更新 更多