Javascript 如何在ionic 1/angular 1中预缓存url内容?

Javascript 如何在ionic 1/angular 1中预缓存url内容?,javascript,angularjs,ionic-framework,angular-cache,Javascript,Angularjs,Ionic Framework,Angular Cache,我对爱奥尼亚很陌生,我正在开发一个应用程序,在这个应用程序中,你加载了一堆类别,然后是类别中的项目列表,当你点击类别中的项目时,documenturl加载的内容基本上是一个图像。目前,所有内容都可以加载,但我希望在我的类别可见时预加载内容,因此即使我脱机,我也应该能够单击类别列表中的任何项目并加载相应的文档。我在网上查找过,但除了localstorage之外,我找不到任何东西。localstorage在您访问数据之后而不是之前缓存数据。有没有一种方法可以预加载或预缓存内容 以下是我的控制器代码:

我对爱奥尼亚很陌生,我正在开发一个应用程序,在这个应用程序中,你加载了一堆类别,然后是类别中的项目列表,当你点击类别中的项目时,documenturl加载的内容基本上是一个图像。目前,所有内容都可以加载,但我希望在我的类别可见时预加载内容,因此即使我脱机,我也应该能够单击类别列表中的任何项目并加载相应的文档。我在网上查找过,但除了localstorage之外,我找不到任何东西。localstorage在您访问数据之后而不是之前缓存数据。有没有一种方法可以预加载或预缓存内容

以下是我的控制器代码:

 angular.module('starter.controllers', ["utility.services"])
  .directive("bindCompiledHtml", ["$compile", "zoomPerOrientation", function($compile, zoomPerOrientation) {
    return {
      template: '<div></div>',
      scope: {
        rawHtml: '=bindCompiledHtml'
      },
      link: function(scope, elem, attrs) {
        scope.$watch('rawHtml', function(value) {
          if (!value) return;
          var newElem = $compile(value)(scope.$parent);
          elem.contents().remove();
          zoomPerOrientation.zoomTo('docScroll');
          elem.append(newElem);
          elem.bind("click", function(e) {
            e.stopPropagation();
            e.preventDefault();
            if (e.target.tagName === 'A') {
              window.open(encodeURI(e.target.href), '_system', "presentationstyle=fullscreen,closebuttoncaption=close,location=no,transitionstyle=fliphorizontal");
              return false;
            } else if (e.target.parentNode.tagName === 'A') {
              window.open(encodeURI(e.target.parentNode.href), '_system', "presentationstyle=fullscreen,closebuttoncaption=close,location=no,transitionstyle=fliphorizontal");
              return false;
            }
          });
        });
      }
    };
  }])
  .directive('setHeight', function($window) {
    return {
      link: function(scope, element, attrs) {
        element.css('height', $window.innerHeight + 30);
      }
    }
  })
  .controller("MenuCtrl", ["$scope", "MenuService", "$stateParams", "$state", "ConfigUrls", function($scope, MenuService, $stateParams, $state, ConfigUrls) {
    //  debugger;
    console.log("MenuCtrl");

    $scope.menuData = [];
    $scope.noMenuDataMsg = "Loading....";
    $scope.LoadMenu = function(forceLoad) {
      console.log("MenuCtrl - LoadMenu");

      //  console.log(MenuService.getClinicalAreas(forceLoad));
      MenuService.getClinicalAreas(forceLoad).then(function(data) {
        $scope.menuData = data;
      }, function(err) {
        console.log(err);
        if (err.error === "timeout") {
          $scope.noMenuDataMsg = "Error: Unable to retrieve data due to network error! Please try again when you are in network."
        } else {
          $scope.noMenuDataMsg = "Error retrieving data! Please contact system administrator."
        }
        $scope.menuData = [];
      }).finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    }
    $scope.deviceModel = window.localStorage.getItem("deviceModel");
    // console.log(MenuService);
    // console.log($scope.menuData);
    $scope.title = $stateParams.topTitle;
    var metaTag = $stateParams.metaTag;
    //console.log(ConfigUrls[metaTag+"Published"]);
    if (metaTag !== "") {
      window.localStorage.setItem('publishedUrl', ConfigUrls[metaTag + "Published"]);
      window.localStorage.setItem('docUrl', ConfigUrls[metaTag + "DocUrl"]);
      window.localStorage.setItem('cacheKeyPrefix', metaTag);

      $scope.LoadMenu(false);
    } else {
      $scope.noMenuDataMsg = "Under Construction!";
    }

    //console.log("metaTag",metaTag);
    //if ($stateParams.topTitle === "Transplant") {
    //    $scope.LoadMenu(false);
    //}
    //else {
    //    $scope.noMenuDataMsg = "Under Construction!";
    //}
    $scope.showHomeItem = function(clinicalArea) {
      console.log("MenuCtrl - showHomeItem");

      $state.go('contr.home', {
        cA: clinicalArea
      });
    }
    $scope.goHome = function() {
      console.log("MenuCtrl - goHome");

      $state.go('contr.topmenu');
    }
  }])
  .controller("HomeCtrl", ["$scope", "HomeService", "$stateParams", "$state", function($scope, HomeService, $stateParams, $state) {


    console.log("HomeCtrl");

    $scope.organs = [];
    $scope.title = $stateParams.cA;
    $scope.LoadHome = function(forceLoad) {
      console.log("HomeCtrl - LoadHome");

      HomeService.getOrgans($stateParams.cA, forceLoad).then(function(data) {
        $scope.organs = data;
      }, function(err) {
        $scope.organs = [];
      }).finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    }
    $scope.showLevel2Item = function(title, clinicalArea) {
      console.log("HomeCtrl - showLevel2Item");

      $state.go('contr.level2', {
        title: title,
        cA: clinicalArea
      });
      //:title/:cA
    }

    $scope.goHome = function() {
      console.log("HomeCtrl - goHome");

      $state.go('contr.topmenu');
    }

    $scope.LoadHome(false);

  }])
  .controller('Level2Ctrl', ["$scope", "OrganService", "$stateParams", "$state", function($scope, OrganService, $stateParams, $state) {
    $scope.title = "Level2 ";

    console.log("Level2Ctrl");

    $scope.parentOrgan = {};
    $scope.viewTitle = $stateParams.title;

    OrganService.getSingleOrganDetail($stateParams.cA, $stateParams.title).then(function(data) {
      $scope.parentOrgan = data[0];
      $scope.parentOrgan.clinicalAreaDisp = "Transplant";
    }, function(err) {
      $scope.parentOrgan = {};
    });

    console.log($scope.parentOrgan);

    $scope.subGroup = [];

    $scope.LoadSubGroups = function(forceLoad) {
      console.log("Level2Ctrl - LoadSubGroups");
      OrganService.getSubGroups($stateParams.title, $stateParams.cA, forceLoad).then(function(data) {
        $scope.subGroup = data;
        console.log("$scope.subGroup", $scope.subGroup);
      }, function(err) {
        $scope.subGroup = [];
      }).finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    }


    //$scope.deviceModel = window.localStorage.getItem("deviceModel");
    //$scope.devicePlatform = window.localStorage.getItem("devicePlatform");

    $scope.toggleGroup = function(group) {
      group.show = !group.show;
    };
    $scope.isGroupShown = function(group) {
      return group.show;
    };
    $scope.showDocumentDtl = function(id, docTitle, sgName, mnGroup, area) {
      console.log("Level2Ctrl - showDocumentDtl");

      $state.go('contr.doc-dtl', {
        id: id,
        docTitle: docTitle,
        sgName: sgName,
        mnGroup: mnGroup,
        area: area
      });
      //:title/:cA
    }
    $scope.goHome = function() {
      console.log("Level2Ctrl - goHome");
      $state.go('contr.topmenu');
    }
    $scope.LoadSubGroups();
  }])
  .controller('DocumentCtrl', ["$scope", "DocmentService", "zoomPerOrientation", "$stateParams", "$ionicScrollDelegate", "$state", function($scope, DocmentService, zoomPerOrientation, $stateParams, $ionicScrollDelegate, $state) {
    $scope.viewData = {};
    $scope.snippet = "<p style='margin-top:40%;margin-left:40%;font-weight:bold;font-size:1.6em;' class='item item-stable'>Loading...</p>";
    $scope.statusMessage = "";
    $scope.title = $stateParams.mnGroup;

    console.log("DocumentCtrl");

    console.log("$stateParams", $stateParams);
    //, $stateParams.docTitle, $stateParams.sgName, $stateParams.mnGroup, $stateParams.area
    // console.log("Inside docuemtn controller");
    $scope.LoadDocument = function(forceLoad) {
      console.log("DocumentCtrl - LoadDocument");
      DocmentService.getRowDocument($stateParams.id, $stateParams.docTitle, $stateParams.sgName, $stateParams.mnGroup, $stateParams.area, forceLoad).then(
        function(data) {
          // console.log("successfull", data);
          $scope.viewData = data;
          $scope.snippet = $scope.viewData.document;
        },
        function(reason) {
          //  console.log("Error Occured", reason);
          $scope.viewData = {
            "docTitle": "Error Occured!"
          };
          if (reason.error === "timeout") {
            $scope.snippet = "<div style='margin-top:40%;margin-left:15%;font-weight:bold;font-size:1.6em;width:600px !important;padding:16px !important;line-height:120%;' class='item item-stable item-text-wrap item-complex'>Error: Unable to the load the document at this time. Please make sure you are in the network or you have already fetched the document while you were in the network!</div>";
          }
          //  $scope.statusMessage = err;
        }).finally(function() {
        console.log("finally", data);
        $scope.$broadcast('scroll.refreshComplete');
      });
    }

    //below code would be refactored in near future.
    //It is not a good practice adding window event listener in the controller
    window.addEventListener('orientationchange', function() {
      try {
        if ($ionicScrollDelegate.$getByHandle('docScroll')._instances.length > 2) {
          zoomPerOrientation.zoomTo('docScroll');
        }
      } catch (exception) {
        console.log(exception);
      }

    });
    $scope.goHome = function() {
      console.log("DocumentCtrl - goHome");
      $state.go('contr.topmenu');
    }

    $scope.LoadDocument(true);
  }])
  .controller('TopMenuCtrl', ["$scope", "TopMenuService", "$state", "$ionicHistory",
    function($scope, TopMenuService, $state, $ionicHistory) {
      $ionicHistory.clearHistory();
      $scope.title = "Rules";
      $scope.menuItems = [];
      $scope.menuItemsLandscape = [];
      $scope.flatMenuItems = [];
      $scope.tileView = true;
      $scope.listView = false;
      $scope.portraitMode = true;

      console.log("TopMenuCtrl");

      TopMenuService.getMenuItems().then(function(data) {
          $scope.menuItems = data.colData;
          $scope.flatMenuItems = data.flatData;
          $scope.menuItemsLandscape = data.threeColData;
          console.log($scope.menuItems);
        },
        function() {
          $scope.menuItems = [];
        });

      $scope.showMenuItem = function(title, metaTag) {
        console.log("TopMenuCtrl - showMenuItem");

        //$state.go('tab.menu', { topTitle: title });
        $state.go('contr.menu', {
          topTitle: title,
          metaTag: metaTag
        });
      }

      $scope.itemChanged = function() {
        console.log("TopMenuCtrl - itemChanged");

        console.log($scope.tileView);
        if ($scope.tileView) {
          $scope.listView = true;
          $scope.tileView = false;

        } else {
          $scope.listView = false;
          $scope.tileView = true;
        }
      }
      //  console.log(window.orientation);
      function onChangeOrientation() {
        console.log("TopMenuCtrl - onChangeOrientation");

        try {
          //landscape mode
          // console.log("Orientation Changed");

          if (window.orientation === 90 || window.orientation == -90) {
            $scope.portraitMode = false;
          }
          //portrait
          else {
            $scope.portraitMode = true;
          }
        } catch (exception) {
          console.log(exception);
        }
      }

      onChangeOrientation();
      window.addEventListener('orientationchange', function() {
        try {
          //landscape mode
          // console.log("Orientation Changed");

          if (window.orientation === 90 || window.orientation == -90) {
            $scope.$apply(function() {
              $scope.portraitMode = false;
            });
          }
          //portrait
          else {
            $scope.$apply(function() {
              $scope.portraitMode = true;
            });
          }
        } catch (exception) {
          console.log(exception);
        }

      });

    }
  ])
  .controller('LoginController', ["$scope", "$location", "$ionicHistory", '$timeout', '$ionicLoading', '$state',
    function($scope, $location, $ionicHistory, $timeout, $ionicLoading, $state) {

      $scope.username = "Guest";
      $scope.password = "Abcd123";
      // $ionicNavBarDelegate.showBar(false);
      $scope.login = function(password) {
        console.log("LoginController - login");

        if (password) {
          $ionicLoading.show({
            content: 'Loading',
            animation: 'fade-in',
            showBackdrop: true,
            template: '<p class="item-icon-left bar-header"><ion-spinner icon="lines"/></p>',
            maxWidth: 200,
            showDelay: 0
          });
          window.localStorage.setItem("Pswd", password);
          $ionicHistory.nextViewOptions({
            disableAnimate: true,
            disableBack: true
          });

          $timeout(function() {
            $ionicLoading.hide();
            //$location.path("/tab/topmenu");
            $state.go('contr.topmenu');
          }, 1000);
        }
      }
    }
  ])
  .controller('AccountCtrl', function($scope) {
    $scope.settings = {
      enableFriends: true
    };
  });
angular.module('starter.controllers',[“utility.services”])
.directive(“bindCompiledHtml”,[“$compile”,“zoomPerOrientation”,函数($compile,zoomPerOrientation){
返回{
模板:“”,
范围:{
rawHtml:'=bindCompiledHtml'
},
链接:功能(范围、要素、属性){
范围.$watch('rawHtml',函数(值){
如果(!value)返回;
var newElem=$compile(值)(范围$parent);
elem.contents().remove();
zoomPerOrientation.zoomTo('docScroll');
附加元素(newElem);
元素绑定(“点击”,函数(e){
e、 停止传播();
e、 预防默认值();
如果(e.target.tagName=='A'){
window.open(encodeURI(e.target.href),“\u system”,“presentationstyle=fullscreen,CloseButtonCoption=close,location=no,transitionstyle=fliphorizontal”);
返回false;
}else if(e.target.parentNode.tagName==='A'){
window.open(encodeURI(e.target.parentNode.href),“\u system”,“presentationstyle=fullscreen,CloseButtonCoption=close,location=no,transitionstyle=fliphorizontal”);
返回false;
}
});
});
}
};
}])
.directive('setHeight',函数($window){
返回{
链接:函数(范围、元素、属性){
css('height',$window.innerHeight+30);
}
}
})
.controller(“MenuCtrl”、[“$scope”、“MenuService”、“$stateparms”、“$state”、“ConfigUrls”、函数($scope、MenuService、$stateparms、$state、ConfigUrls){
//调试器;
console.log(“MenuCtrl”);
$scope.menuData=[];
$scope.noMenuDataMsg=“加载…”;
$scope.LoadMenu=函数(强制加载){
log(“MenuCtrl-LoadMenu”);
//log(MenuService.getClinicalAreas(forceLoad));
MenuService.getClinicalAreas(forceLoad).then(函数(数据){
$scope.menuData=数据;
},函数(err){
控制台日志(err);
如果(err.error==“超时”){
$scope.noMenuDataMsg=“错误:由于网络错误,无法检索数据!请在网络中重试。”
}否则{
$scope.noMenuDataMsg=“检索数据时出错!请与系统管理员联系。”
}
$scope.menuData=[];
}).最后(函数(){
$scope.$broadcast('scroll.refreshComplete');
});
}
$scope.deviceModel=window.localStorage.getItem(“deviceModel”);
//console.log(MenuService);
//log($scope.menuData);
$scope.title=$stateParams.topTitle;
var metaTag=$stateParams.metaTag;
//log(配置URL[metaTag+“已发布”]);
如果(元标记!==“”){
window.localStorage.setItem('publishedUrl',ConfigUrls[metaTag+“Published”]);
window.localStorage.setItem('docUrl',ConfigUrls[metaTag+“docUrl]”);
setItem('cacheKeyPrefix',metaTag);
$scope.LoadMenu(false);
}否则{
$scope.noMenuDataMsg=“正在施工!”;
}
//log(“metaTag”,metaTag);
//如果($stateParams.topTitle==“移植”){
//$scope.LoadMenu(false);
//}
//否则{
//$scope.noMenuDataMsg=“正在施工!”;
//}
$scope.showHomeItem=功能(clinicalArea){
log(“MenuCtrl-showHomeItem”);
$state.go('CONTRL.home'){
cA:临床区域
});
}
$scope.goHome=函数(){
log(“MenuCtrl-goHome”);
$state.go('control.topcmenu');
}
}])
.controller(“HomeCtrl”、[“$scope”、“HomeService”、“$stateparms”、“$state”、函数($scope、HomeService、$stateparms、$state){
console.log(“HomeCtrl”);
$scope.organs=[];
$scope.title=$stateParams.cA;
$scope.LoadHome=函数(forceLoad){
log(“HomeCtrl-LoadHome”);
getOrgans($stateParams.cA,forceLoad)。然后(函数(数据){
$scope.organs=数据;
},函数(err){
$scope.organs=[];
}).最后(函数(){
$scope.$broadcast('scroll.refreshComplete');
});
}
$scope.showLevel2Item=功能(标题,临床区域){
log(“HomeCtrl-showLevel2Item”);
$state.go('CONTRL.level2'{
标题:标题,,
cA:临床区域
});
//:title/:cA
}
$scope.goHome=函数(){
log(“HomeCtrl-goHome”);
$state.go('control.topcmenu');
}
$scope.LoadHome(假);
}])
.controller('Level2Ctrl',[“$scope”,“OrganService”,“$stateparms”,“$state”,function($scope,OrganService,$stateparms,$state){
$scope.title=“Level2”;
控制台日志(“Level2Ctrl”);
$scope.parentOrgan={};
$scope.viewTitle=$stateParams.title;
getSingleOrganDetail($stateParams.cA,$stateParams.title)。然后(函数(数据){
$scope.parentOrgan=数据[0];
$scope.parentOrgan.clinicalAreaDisp=“移植”;
},函数(err){
$scope.parentOrgan={};
});
console.log($scope.parentOrgan);
$scope.subGroup=[];
$scope.LoadSubGroups=函数(forceLoad){
log(“Level2Ctrl-LoadSubGroups”);
OrganService.getSubGroups($stateParams.title、$stateParams.cA、forceLoad)。