UNPKG

cheeky-angular

Version:
140 lines (120 loc) 5.61 kB
<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="main.css"> <script src="/bower_components/angular/angular.min.js"></script> <script src="/bower_components/angular-sanitize/angular-sanitize.min.js"></script> <script src="/bower_components/angular-cache/dist/angular-cache.min.js"></script> <script src="/bower_components/lodash/lodash.min.js"></script> <script> angular.module('app', ['ngSanitize', 'angular-cache']) .run(function($rootScope, $http, contentService){ // $rootScope.content = { // msgs: { // welcome: 'Hello!' // } // }; contentService.get().then(function(data){ $rootScope.content = data; }); }) .directive('editable', function($rootScope, $parse, $compile, $sce, contentService){ var template = [ '<span class="editor" contentEditable="true"></span>', '<div class="tools" ng-show="isEditing">', ' <button class="btn" ng-click="cancel()">Cancel</button>', ' <button class="btn" ng-click="save()">Save</button>', ' <button class="btn" ng-click="history()">History</button>', '</div>' ].join('\r\n'); return { require: '?ngModel', template: template, scope: {}, link: function(scope, element, attrs, ngModel){ if(!ngModel) return; var path = attrs.ngModel, editor = element.children().eq(0), transientValue; // render the html when the model changes ngModel.$render = function(){ transientValue = ngModel.$viewValue || ''; editor.html($sce.getTrustedHtml(transientValue)); }; // enable 2 way binding on change editor.on('blur keyup change', function(){ scope.$evalAsync(function(){ var html = editor.html(); ngModel.$setViewValue(html); endEditing(); }); }); editor.on('focus', function(){ scope.$evalAsync(function(){ beginEditing(); }); }); // expose scope scope.cancel = cancelChanges; scope.save = saveChanges; function beginEditing(){ scope.isEditing = true; } function endEditing(){ scope.isEditing = ngModel.$dirty; } function finalizeEditing(){ ngModel.$setPristine(); endEditing(); } function cancelChanges(){ ngModel.$setViewValue('Welcomes!') ngModel.$render(); finalizeEditing(); } function saveChanges(){ contentService.udpate(path, transientValue); finalizeEditing(); } } }; }) .factory('contentService', function($q, $http, CacheFactory){ CacheFactory('contentService', { maxAge: 15 * 60 * 1000, cacheFlushInterval: 60 * 60 * 1000, deleteOnExpire: 'aggressive', storageMode: 'localStorage' }); return { get: function(){ var deferred = $q.defer(); $http.get('content.json', { cache: CacheFactory.get('contentService') }).success(function (data) { deferred.resolve(data); }); return deferred.promise; } }; }) .controller('default', function(){ }); </script> </head> <body> <p>Templating Performance Test</p> <div ng-app="app"> <div ng-controller="default"> <p> <editable path="content.msgs.welcome" ng-model="content.msgs.welcome"></editable> </p> <hr/> <p> {{content.msgs.welcome}} </div> </div> </body> </html>