AngularJS 1.0.2 CacheFactory Example
by johnwun
HTML
<div ng-app="someApp">
<div ng-controller="SomeController">
<input ng-model="equation" on-enter="calculate()"/>
<button ng-click="calculate()">calculate</button><br/>
<input ng-model="result"/> {{status}}<br/>
{{cacheInfo}}<br/>
<button ng-click="clearCache()">clear cache</button>
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
JavaScript
angular.module('someApp', []).
factory('SomeCache', function($cacheFactory) {
return $cacheFactory('someCache', {
capacity: 3 // optional - turns the cache into LRU cache
});
}).
directive('onEnter', function() {required(optional) – {string=} – Sets required validation error key if the value is not entered.
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.onEnter);
});
event.preventDefault();
}
});
};
});
var SomeController = function($scope, SomeCache) {
$scope.calculate = function() {
var equation = $scope.equation,
result = SomeCache.get(equation),
status = 'pulled from cache';
if (!result) {
status = 'evaluated';
result = eval(equation);
SomeCache.put(equation, result);
}
$scope.result = result;
$scope.status = status;
$scope.cacheInfo = SomeCache.info();
}
$scope.clearCache = function() {
SomeCache.removeAll();
$scope.cacheInfo = SomeCache.info();
}
}