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