Last active
December 28, 2015 08:09
-
-
Save EpokK/7469456 to your computer and use it in GitHub Desktop.
clickToEdit directive with AngularJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}; | |
} | |
}; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div click-to-edit="someModelName" on-save="saveMe()"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.