Skip to content

Instantly share code, notes, and snippets.

@EpokK
Last active December 28, 2015 08:09
Show Gist options
  • Save EpokK/7469456 to your computer and use it in GitHub Desktop.
Save EpokK/7469456 to your computer and use it in GitHub Desktop.
clickToEdit directive with AngularJS
app.directive("clickToEdit", function() {
var editorTemplate = '<div class="click-to-edit">' +
'<div ng-hide="view.editorEnabled">' +
'{{value}} ' +
'<a ng-click="enableEditor()">Edit</a>' +
'</div>' +
'<div ng-show="view.editorEnabled">' +
'<input ng-model="view.editableValue">' +
'<a href="#" ng-click="save()">Save</a>' +
' or ' +
'<a ng-click="disableEditor()">cancel</a>.' +
'</div>' +
'</div>';
return {
restrict: "A",
replace: true,
template: editorTemplate,
scope: {
value: "=clickToEdit",
onSave: "&onSave"
},
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();
$scope.onSave();
};
}
};
});
<div click-to-edit="someModelName" on-save="saveMe()"></div>
@expntly
Copy link

expntly commented Mar 6, 2014

Very nice! How to make it work so it shares the scope with the controller it's in? I don't really understand how to pass the new value back to the controller's scope then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment