Angular JS 和复杂指令 [英] Angular JS and Complex Directives

查看:22
本文介绍了Angular JS 和复杂指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个 AngularJS 小部件,它用可编辑的文本字段替换标签.单击文本会将其替换为输入字段,然后在输入上按 Enter 会更新现有资源.

This is an AngularJS widget which replaces a tag with an editable text field. Clicking the text replaces it with an input field, and hitting enter on the input updates an existing resource.

我对自己生成的代码不满意.所有这些 evals 和应用程序真的有必要吗?我该如何改进?

I am not happy with the code I produced. Are all of these evals and applys really necessary? How can I improve this?

使用

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}}

推荐答案

我建议不要将 jQuery 与 Angular 一起使用,尤其是在您正在学习的时候.您所做的一切都不需要它.

I would recommend not using jQuery with Angular, especially as you're learning. None of what you're doing requires it.

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

  1. You can get rid of the first use of click callback by using ngClick in your template:

<span class="editableTextField" ng-click="showEdit = true">

  • 您可以使用 Angular-UI 摆脱 keyup 回调购买:

    <input class="edit" ... ui-keypress="{enter: 'handleEnter()'}">
    

  • 我建议使用双向绑定,以便您可以正确地将数据写回作用域.

  • I'd recommend using a two-way binding so you can write data back to the scope properly.

    当你连接 $watch 时,你会得到新值作为第一个参数.这将为您节省另一个 $eval.

    When you wire up $watch, you get the new value as the first argument. That will save you another $eval.

    这是给你的小提琴... http://jsfiddle.net/maU9t/

    Here's a fiddle for you... http://jsfiddle.net/maU9t/

    这篇关于Angular JS 和复杂指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆