Skip to content

Instantly share code, notes, and snippets.

@tristar500
Created May 15, 2014 18:22
Show Gist options
  • Save tristar500/03570e8ffd6f81c7d9d0 to your computer and use it in GitHub Desktop.
Save tristar500/03570e8ffd6f81c7d9d0 to your computer and use it in GitHub Desktop.
Click to Edit Angular Directive
//
//http://icelab.com.au/articles/levelling-up-with-angularjs-building-a-reusable-click-to-edit-directive/
//
// The prepend attribute allows you to add text before the value
//
// <p class="form-control-static" click-to-edit="user.bill_rate" prepend="$"></p>
//
//
app.directive("clickToEdit", function() {
var editorTemplate = '<div class="click-to-edit">' +
'<div ng-hide="view.editorEnabled">' +
'{{prepend}}{{value}} ' +
'<a ng-click="enableEditor()" title="Edit"><i class="fa fa-pencil" style="cursor:pointer;"></i></a>' +
'</div>' +
'<div ng-show="view.editorEnabled">' +
'<input ng-model="view.editableValue">' +
'<a href="#" ng-click="save()" title="Save"><i class="fa fa-check-circle text-success" style="cursor:pointer;"></i></a>' +
'&nbsp;' +
'<a ng-click="disableEditor()" title="Cancel"><i class="fa fa-minus-circle text-warning" style="cursor:pointer;"></i></a>' +
'</div>' +
'</div>';
return {
restrict: "A",
replace: true,
template: editorTemplate,
scope: {
value: "=clickToEdit",
prepend: "@prepend"
},
controller: function($scope) {
$scope.view = {
editableValue: $scope.value,
editorEnabled: false
};
$scope.enableEditor = function() {
$scope.view.editorEnabled = true;
$scope.view.editableValue = $scope.value;
};
$scope.disableEditor = function() {
$scope.view.editorEnabled = false;
};
$scope.save = function() {
$scope.value = $scope.view.editableValue;
$scope.disableEditor();
};
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment