Skip to content

Instantly share code, notes, and snippets.

@BernhardPosselt
Last active December 21, 2015 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BernhardPosselt/6264458 to your computer and use it in GitHub Desktop.
Save BernhardPosselt/6264458 to your computer and use it in GitHub Desktop.
Edit fields like in GMail contacts: Hover over text to show input field and fire callback when it actually changed
editable:hover span {
display: none;
}
editable span.editing {
display: none;
}
editable input {
display: none;
}
editable:hover input {
display: block;
}
editable input.editing {
display: block;
}
angular.module('Demo', []).directive('editable', ['$parse', function ($parse) {
return {
restrict: 'E',
scope: {
value: '@',
onChange: '&'
},
template: '<span ng-class="{editing: editing}" >{{ value }}</span>' +
'<input ng-click="editing=true" ng-class="{editing: editing}" ' +
'type="text" ng-model="value" />',
link: function (scope, element, attributes) {
// set the old value first time when its linked, this value is then
// updated inside the apply
var oldValue = attributes.value;
var changedCallback = function () {
scope.$apply(function () {
scope.editing = false;
if(scope.value !== oldValue) {
$parse(attributes.onChange)(scope.$parent);
oldValue = scope.value;
}
})
};
element.find('input').
on('blur', changedCallback).
on('keyup', function (event) {
// enter also triggers a callback
if(event.keyCode === 13) {
changedCallback();
}
});
}
}
}]);
<!DOCTYPE html>
<html ng-app="Demo">
<head>
<title>Demo</title>
<link rel="stylesheet" type="text/css" href="app.css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-init="numChanges=0">
<editable value="change me" on-change="numChanges=numChanges+1"></editable>
<p>Changed field {{ numChanges }} times</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment