2014-06-22 2 views
0

URL (라우터 ui)에 즉시 액세스 할 수 있도록 앱로드시 캐싱해야하는 동적 JSON 콘텐츠로 데모 앱을 제작하려고합니다.앱로드시 Angular로 동적 (JSON) 콘텐츠를 캐싱하려면 어떻게해야합니까?

상단에 링크 "잭 버튼보기 정보는"단지 이전에로드 된 유일의 후 자신의 정보를 보여줍니다 (그렇다하더라도, 그것은 터져입니다) :

예 plunker : 나는 액세스해야 http://plnkr.co/edit/xIzq8cy4ZsZC9Dz5Cbpv?p=preview

앱 전체의 다른 링크에서 '사람'에 대한 콘텐츠가있는 경우, 인앱 URL을 통해 추측하고 있습니다. 모범 사례가 무엇인지 확실하지 않습니다.

감사합니다.

HTML

index.html 

    <div class="row"> 
    <div class="col-sm-12"> 
     <a ng-href="#/" class="btn-link">Home</a> | 
     <a ng-href="#/jack-burton">View Info for Jack Burton (Only works after it's cached)</a> 
     <div class="well" ui-view></div> 
    </div> 
    </div> 


home.html 

    <h1>People</h1> 

    <ul class="list-unstyled"> 
    <li ng-repeat="person in people"> 
     <a ng-href="#/{{ person.url }}" ng-click="setPeopleContent(person)"> 
     {{person.name}} 
     </a> 
    </li> 
    </ul> 

person.html 

    <h1>{{peopleContent.name}}</h1> 

    <section id="contact" ng-if="peopleContent.hasContact"> 
     <h4>Contact Info</h4> 
     <p ng-repeat="item in peopleContent.contact" ng-if="contentExists(item.address)"> 
     Address: {{item.address}} 
     </p> 
     <p ng-repeat="item in peopleContent.contact" ng-if="contentExists(item.phone)"> 
     Phone: {{item.phone}} 
     </p> 
     <p ng-repeat="item in peopleContent.contact" ng-if="contentExists(item.email)"> 
     Email: {{item.email}} 
     </p> 
    </section> 

    <section id="pastJobs" ng-if="peopleContent.hasPastJobs"> 
     <h4>Past Jobs</h4> 
     <p ng-repeat="item in peopleContent.pastJobs" ng-if="contentExists(item.job)"> 
      Job: {{item.job}} 
     </p> 
     <p ng-repeat="item in peopleContent.pastJobs" ng-if="contentExists(item.jobTitle)"> 
      Title: {{item.jobTitle}} 
     </p> 
    </section> 

    <section id="goals" ng-if="peopleContent.hasGoals"> 

     <h4>Goals</h4> 
     <ul class="list-unstyled"> 
     <li ng-repeat="item in peopleContent.goals" ng-if="contentExists(item.goal)"> 
      {{item.goal}} 
     </li> 
     </ul> 

    </section> 

JSON

{ 
     "people": [ 

      { 
       "name": "Alexander Supertramp", 
       "url": "alexander-supertramp", 
       "contact": [ 
        { 
         "address": "Alaska" 
        } 
        ], 
       "goals": [ 
        { 
         "goal": "Climb Mt Everest" 
        }, 
        { 
         "goal": "Travel in space" 
        }, 
        { 
         "goal": "Become a rocket scientist" 
        } 
       ] 

      }, 
      { 
       "name": "Gordon Bombay", 
       "url": "gordon-bombay", 
       "pastJobs": [ 
        { 
         "job": "Hockey Coach", 
         "jobTitle": "Coach" 
        }, 
        { 
         "job": "Hockey Player", 
         "jobTitle": "Goalie" 
        } 
        ], 
       "goals": [ 
        { 
         "goal": "Win the stanley cup" 
        }, 
        { 
         "goal": "Be a cool guy" 
        } 
       ] 
      }, 
      { 
       "name": "Jack Burton", 
       "url": "jack-burton", 
       "contact": [ 
        { 
         "address": "China Town", 
         "phone": "555-555-getMyTruckBack", 
         "email": "[email protected]" 
        } 
        ], 
       "pastJobs": [ 
        { 
         "job": "Porkchop Express Driver", 
         "jobTitle": "Truck Driver" 
        } 
        ], 
       "goals": [ 
        { 
         "goal": "Get his truck back" 
        }, 
        { 
         "goal": "Stay alive" 
        }, 
        { 
         "goal": "Get with Kim Cattrall" 
        } 
       ] 
      }, 
       { 
       "name": "Eric Roberts", 
       "url": "eric-roberts", 
       "contact": [ 
        { 
         "address": "New York City", 
         "email": "[email protected]" 
        } 
        ], 
       "goals": [ 
        { 
         "goal": "Become a comicbook artist" 
        }, 
        { 
         "goal": "Find that woman from the street" 
        }, 
        { 
         "goal": "Stay alive" 
        }, 
        { 
         "goal": "Don't get run over by an evil ambulance" 
        } 
       ] 
      } 
     ] 
    } 

JS

var myapp = angular.module('demoApp', ["ui.router"]) 
myapp.config(function($stateProvider, $urlRouterProvider){ 

    $stateProvider 
    .state('home', { 
     url: "/", 
     templateUrl: "home.html" 
    }) 
    .state('person', { 
     url: "/:person", 
     templateUrl: "person.html" 
    }) 

    $urlRouterProvider.otherwise("/") 
}); 


function MainController($scope, $http, $stateParams) { 

    $http.get('demo-data.json', { cache: true}).success(function(data){ 
    $scope.people = data.people; 
    }); 

    $scope.person = $stateParams.person; 

    $scope.setPeopleContent = function(person) { 
    $scope.peopleContent = person; 
    $scope.peopleContent.hasContact = ($scope.peopleContent.contact instanceof Array); 
    $scope.peopleContent.hasPastJobs = ($scope.peopleContent.pastJobs instanceof Array); 
    $scope.peopleContent.hasGoals = ($scope.peopleContent.goals instanceof Array); 
    }; 

    // Checks if contentValue is undefined/exists 
    $scope.contentExists = function(contentValue) { 
    if(contentValue != undefined) { 
     return true; 
    } 
    }; 

}; 
+0

[로컬 저장소] (http://diveintohtml5.info/storage.html)를 사용하십시오. 클라이언트 측에서 일부 정보를 저장하기 위해 만들어진 것입니다. 그래도 무효화를 구현해야합니다. – Tommi

+0

감사합니다 Tommi, 각도 응용 프로그램에서 로컬 저장소에 접근하는 가장 좋은 방법은 무엇인지 알고 있습니까? – MuddyMudSkipper

+0

게시 된 링크는 정말 좋은 자습서를 포함하고 있으며, 나보다 잘 설명 할 수 있습니다. – Tommi

답변

0
당신은 로컬 스토리지 또는 sessionStorage 중 하나가 여기에 대한 추가 정보를 원하시면입니다 사용해야

: link

다음은 각도로 사용하는 방법의 한 예입니다.

참고 마지막으로 데이터를 저장 공간에 저장 한 날짜를 저장합니다 (데이터가 너무 오래되면 서버에서 데이터를 다시 가져 와서 저장합니다). 저장소에 저장)

var retreivedStorageData = JSON.parse(window.sessionStorage.getItem("basicUserInfo")); 
if (retreivedStorageData) { 
    var differenceInMs = Math.abs(new Date() - new Date(retreivedStorageData.date)); 
    // check how old is data 
    if (differenceInMs <= 60 * 1000) { 
     $scope.ImageUrl = retreivedStorageData.item.ImageUrlSmall; 
     $scope.UserName = retreivedStorageData.item.Name; 


    } else { 
    //if it's too old get it from server 
     getDataFromServer(); 
    } 
} else { 
    getDataFromServer(); 
} 

function getDataFromServer() { 
     $http.get("/Profile/GetUserBasicInfo/") 
      .success(function(result) { 

       /*More code here*/ 

       if (typeof (window.Storage) != "undefined") { 

        var storageData = JSON.stringify({ item: result, date: new Date() }); 
        window.sessionStorage.setItem("basicUserInfo", storageData); 
       } 




      }); 
    } 
+0

감사! 저는이 점들과 점들을 연결 시키려고 노력하고 있고, 어떻게 생각하는지 다시 생각하고 있습니다. 지금은 조건부로 json 배열을 사용할 수 있는지 확인합니다. 그렇다면 내용이 추가됩니다. 로컬 저장소로 일하는 것에 대해 어떻게 생각하는지 모르겠습니다. – MuddyMudSkipper

관련 문제