[英]Angular JS and Complex Directives
這是一個AngularJS小部件,將標簽替換為可編輯的文本字段。 單擊文本將其替換為輸入字段,然后在輸入中按Enter鍵將更新現有資源。
我對自己編寫的代碼不滿意。 所有這些評估和應用真的必要嗎? 我該如何改善?
使用
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}}
我建議不要在Angular中使用jQuery,尤其是在學習時。 您所做的一切都不需要它。
您可以通過在模板中使用ngClick
來擺脫首次使用click
回調的功能:
<span class="editableTextField" ng-click="showEdit = true">
您可以使用Angular-UI擺脫購買keyup
回調的keyup
:
<input class="edit" ... ui-keypress="{enter: 'handleEnter()'}">
我建議使用雙向綁定,以便您可以將數據正確寫回到示波器。
連接$watch
,您將獲得新值作為第一個參數。 那將為您節省另外的$eval
。
這是為您准備的小提琴... http://jsfiddle.net/maU9t/
小提琴! http://jsfiddle.net/pvtpenguin/25cqs/17
變化:
創建一個on-enter
指令, editable-text
指令在模板中使用。 新的on-enter
指令可以在任何地方重用。
<input ... on-enter="update()" ... />
使用ng-click
指令可切換showEdit
狀態,而不是依賴於jquery和函數。
<input ... on-click="showEdit = true" ... />
綁定value
對指令的隔離范圍,該指令的模型屬性的值。 這使我們可以刪除scope.$watch
並在本地value
和activeCustomer.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;
}
};
});
這是嵌入式編輯器的一種版本。 http://jsfiddle.net/pUMer/
主要特征:
如果只想在內聯編輯器上使用,請。 將數組元素減小為一。
HTML :
<inline-editor inline-editor-mdl="inlineEditor"></inline-editor>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.