Skip to content

Instantly share code, notes, and snippets.

@EvilScott
Last active August 29, 2015 14:13
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 EvilScott/cfef50a7d6f5ab61d633 to your computer and use it in GitHub Desktop.
Save EvilScott/cfef50a7d6f5ab61d633 to your computer and use it in GitHub Desktop.
Angular Inline Editing Directive
<div class="edit-inline">
<span ng-show="editing">
<input type="text" ng-model="text" />
<button ng-click="editing = false">Save</button>
</span>
<span ng-hide="editing">
<span ng-bind="text"></span>
<button ng-click="editing = true">Edit</button>
</span>
</div>
(function() {
'use strict';
angular
.module('editInline', [])
.directive('editInline', function() {
return {
link: function(scope, _ele, _attrs, _ctrl, transcludeFn) {
var localStorageKey = 'editInline::' + scope.name;
scope.$watch('text', function(newVal) {
localStorage.setItem(localStorageKey, newVal);
});
transcludeFn(function(content) {
var localStorageValue = localStorage.getItem(localStorageKey);
if (localStorageValue) {
scope.text = localStorageValue;
} else {
scope.text = content[0] ? content[0].textContent : 'default text';
}
});
},
restrict: 'E',
scope: { name: '@' },
templateUrl: 'edit-inline.html',
transclude: true
};
});
})();
<!DOCTYPE html>
<html ng-app="editInline">
<head>
<title>Edit Inline</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" />
</head>
<body>
<!-- demo usage -->
<edit-inline name="foo"></edit-inline>
<edit-inline name="bar">default bar text</edit-inline>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.min.js"></script>
<script type="text/javascript" src="/editInline.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment