2013-05-07 93 views
1

这是一个AngularJS小部件,它用一个可编辑的文本字段替换了一个标签。单击文本将其替换为输入字段,然后按输入键更新现有资源。Angular JS和Complex Directives

我对我制作的代码不满意。所有这些证明和应用真的有必要吗?我该如何改进?

要使用

editable-text(model="activeCustomer.phone_number", resource="Customer", field="phone_number") 

的指令代码

.directive("editableText", function($injector){ 
    return { 
    restrict: "E", 
    templateUrl: document.views.directivePartials.editableText, 
    link: function(scope, elem, attrs){ 
     $(elem).find(".noEdit").click(function(){ 
     scope.showEdit = true; 
     scope.$apply(); 
     }); 

     var ENTER = 13; 
     $(elem).find('.edit').keyup(function(event){ 
     if(event.keyCode == ENTER){ 
      var resource = $injector.get(attrs.resource); 

      var params = {}; 
      params[attrs.field] = scope.value 
      resource.update(params); 
      scope.showEdit=false; 
     } 
     }); 

     scope.showEdit = false; 
     scope.$watch(attrs.model, function(){ 
     scope.value = scope.$eval(attrs.model); 
     }); 
    }, 
    }; 
}) 

模板

span.editableTextField 
input.edit(type="text", ng-show="showEdit", ng-model="value") 
span.noEdit(ng-show="!showEdit") {{value}} 

回答

2

我不会使用jQuery与角度建议,尤其是当你正在学习。没有你在做什么需要它。

  1. 您可以通过在你的模板使用ngClick摆脱第一次使用click回调的:

    <span class="editableTextField" ng-click="showEdit = true"> 
    
  2. 可以摆脱keyup回调买入采用了棱角分明的UI:

    <input class="edit" ... ui-keypress="{enter: 'handleEnter()'}"> 
    
  3. 我建议使用双向绑定,以便您可以正确地将数据写回到范围。

  4. 当您连线$watch时,您将获得新的值作为第一个参数。这将为您节省另一个$eval

这里是为您小提琴... http://jsfiddle.net/maU9t/

0

小提琴! http://jsfiddle.net/pvtpenguin/25cqs/17

变化:

  1. 创建的editable-text指令在模板中使用的on-enter指令。新的on-enter指令可以在任何地方重复使用。

    <input ... on-enter="update()" ... /> 
    
  2. 使用ng-click指令切换,而不是依靠jQuery和功能showEdit状态。

    <input ... on-click="showEdit = true" ... /> 
    
  3. 在指令的分离范围该指令的模型属性的值

    绑定value。这让我们删除scope.$watch,并创建一个双向当地valueactiveCustomer.phone_number

    <editable-text model="activeCustomer.phone_number"></editable-text> 
    <input ... ng-model="value" /> 
    <span>{{value}}</span> 
    
    ... 
    
    scope: { 
        // give `value` and `activeCustomer.phone_number two-way binding 
        value: '=model' 
    } 
    

这些变化完全删除jQuery的依赖之间的结合。结果指令:

myApp.directive("editableText", function($injector){ 
    return { 
    restrict: "E", 
    scope: { 
     value: '=model' // Bind `value` to what is declared on the `model` attribute 
    }, 
    templateUrl: "/tpl.html", 
    link: function(scope, elem, attrs){ 
     scope.update = function() { 
      var resource = $injector.get(attrs.resource); 
      var params = {}; 
      params[attrs.field] = scope.value; 
      resource.update(params); 
      scope.showEdit=false; 
     }; 
     scope.showEdit = false; 
    } 
    }; 
}); 
0

这是内联编辑器的一个版本。 http://jsfiddle.net/pUMer/

主要特点:

  • 配置内嵌编辑
  • 单独的范围为各行内编辑器的初始模式,所以它不会与 干扰父范围
  • 查看所有的模型在线编辑

如果你只想在内联编辑器,请。减少数组元素的大小。

HTML

<inline-editor inline-editor-mdl="inlineEditor"></inline-editor>