Last active
December 21, 2015 06:29
-
-
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
This file contains 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
editable:hover span { | |
display: none; | |
} | |
editable span.editing { | |
display: none; | |
} | |
editable input { | |
display: none; | |
} | |
editable:hover input { | |
display: block; | |
} | |
editable input.editing { | |
display: block; | |
} |
This file contains 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
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(); | |
} | |
}); | |
} | |
} | |
}]); |
This file contains 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
<!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