[AngularJS] $http cache

By default your HTTP requests with the $https service in Angular are not cached. By setting some options, you can turn caching on.

 

/**
 * Created by Answer1215 on 12/15/2014.
 */


angular.module('app', ['ngMaterial'])
    .controller('MainCtrl', function(BookmarksService, BookmarksCacheFactory) {
        var mainCtrl = this;
        mainCtrl.bookmarks = [];

        mainCtrl.getBookmarks = function() {
            BookmarksService.getBookmarks().then(function(response) {
                mainCtrl.bookmarks = response.data;
            });
        }

        mainCtrl.removeCache = function() {
            BookmarksCacheFactory.remove('./data/bookmarks.json');
        }
    })


    .service('BookmarksService', function($http, BookmarksCacheFactory) {
        var BookmarksService = {};

        BookmarksService.getBookmarks = function() {
            return $http.get('./data/bookmarks.json', {cache: BookmarksCacheFactory});
        }

        return BookmarksService;
    })


    .factory('BookmarksCacheFactory', function($cacheFactory) {
        return $cacheFactory('bookmarks');
    });

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="//rawgit.com/angular/bower-material/master/angular-material.css">
    <link rel="stylesheet" href="./bower_components/angular-material/themes/indigo-theme.css">
    <link rel="stylesheet" href="./bower_components/angular-material/themes/teal-theme.css">
</head>
<body ng-app="app" ng-controller="MainCtrl as main" >
    <md-content>
        <section  layout="column" layout-align="start start">
            <div ng-repeat="b in main.bookmarks">{{b.title}}</div>
        </section>
    </md-content>
    <md-button ng-click="main.getBookmarks()" class="md-primary md-raised" md-theme="indigo">Load Bookmarks</md-button>
    <md-button ng-click="main.removeCache()" class="md-primary md-raised" md-theme="teal">Clear cache</md-button>
    <!-- Angular Material Dependencies -->
    <script src="//cdn.jsdelivr.net/hammerjs/2.0.4/hammer.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular-animate.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular-aria.js"></script>

    <!-- Angular Material Javascript using RawGit to load directly from `bower-material/master` -->
    <script src="//rawgit.com/angular/bower-material/master/angular-material.js"></script>
    <script src="app.js"></script>
</body>
</html>

 

"Load bookmarks" only work for the first time clicking the button and load the data.

After click "clear cache", then will load data again.

posted @ 2014-12-15 23:57  Zhentiw  阅读(1167)  评论(0编辑  收藏  举报