问题描述
这是一个AngularJS部件取代一个标签,一个可编辑的文本字段。单击文本与输入字段替换它,并在输入按下回车键更新现有的资源。
我不开心的code我公司生产。是否所有这些evals和applys真的有必要吗?我怎样才能提高呢?
要使用
可编辑的文本(型号=activeCustomer.phone_number,资源=客户,现场=PHONE_NUMBER)
该指令code
.directive(editableText功能($喷油器){
返回{
限制:E,
templateUrl:document.views.directivePartials.editableText,
链接:功能(范围,ELEM,ATTRS){
$(ELEM).find(noEdit)。点击(函数(){
scope.showEdit = TRUE;
。范围$适用();
}); VAR ENTER = 13;
$(ELEM).find('编辑')。KEYUP(函数(事件){
如果(event.key code ==进入){
VAR资源= $ injector.get(attrs.resource); 变种PARAMS = {};
PARAMS [attrs.field] = scope.value
resource.update(PARAMS);
scope.showEdit = FALSE;
}
}); scope.showEdit = FALSE;
范围。$腕表(attrs.model,函数(){
。scope.value = $范围的eval(attrs.model);
});
},
};
})
模板
span.editableTextField
input.edit(类型=文本,NG-秀=showEdit,NG-模型=值)
span.noEdit(NG-秀=!showEdit){{值}}
我会建议不使用jQuery与棱角分明,尤其是当你正在学习。你在做什么都不需要了。
-
您可以摆脱第一次使用的
点击
回调使用ngClick
在你的模板:<跨度类=editableTextFieldNG点击=showEdit =真正的>
-
您可以摆脱
KEYUP
回调买入采用了棱角分明的UI:<输入类=编辑... UI键preSS ={输入:'handleEnter()}>
-
我建议你使用的是双向绑定,所以你可以将数据写回正常的范围。
-
在线了
$腕表
,你得到的新值作为第一个参数。这将节省您的另一$ EVAL
。
下面是给你一个小提琴......
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.
I am not happy with the code I produced. Are all of these evals and applys really necessary? How can I improve this?
To use
editable-text(model="activeCustomer.phone_number", resource="Customer", field="phone_number")
The Directive Code
.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);
});
},
};
})
The Template
span.editableTextField
input.edit(type="text", ng-show="showEdit", ng-model="value")
span.noEdit(ng-show="!showEdit") {{value}}
I would recommend not using jQuery with Angular, especially as you're learning. None of what you're doing requires it.
You can get rid of the first use of
click
callback by usingngClick
in your template:<span class="editableTextField" ng-click="showEdit = true">
You can get rid of the
keyup
callback buy using Angular-UI:<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.
When you wire up
$watch
, you get the new value as the first argument. That will save you another$eval
.
Here's a fiddle for you... http://jsfiddle.net/maU9t/
这篇关于角JS和复杂指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!