在Angularjs中保存ng-src的状态

时间:2013-05-14 10:33:54

标签: angularjs local-storage

我正在尝试为Angular.js中的应用程序创建一个可保存的标题图像,到目前为止我有这个代码,也可以作为Plunker here使用:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.bannerState = false;

  $scope.changeHeader = function () {
    $scope.bannerState = true;
  };

  $scope.currentImage = 0;

  $scope.nextButton = function () {
    if ($scope.bannerState) {
      $scope.currentImage++;
    }
    if ($scope.currentImage > ($scope.bannerImages.length - 1)) {
      $scope.currentImage = 0;
    }
  };

  $scope.previousButton = function () {
    if ($scope.bannerState) {
      $scope.currentImage--;
    }
    if ($scope.currentImage < 0) {
      $scope.currentImage = ($scope.bannerImages.length - 1);
    }
  };

  $scope.setHeader = function () {
    $scope.bannerState = false;
  };

  $scope.bannerImages = [
    {
      src: "http://yaocho-digital.com/portfolio/content/threadme1.png"
    },
    {
      src: "http://yaocho-digital.com/portfolio/content/threadme2.png"
    },
    {
      src: "http://yaocho-digital.com/portfolio/content/threadme3.png"
    }
  ];
});

我不知道如何将它存储在一个对象中,以便我可以离开页面然后返回它就在那里!请帮忙!

JP

2 个答案:

答案 0 :(得分:0)

你可以把它放在$ rootScope中 - 只要你的页面没有重置,你就会很好

答案 1 :(得分:0)

HTML 5 local storage可以选择在本地存储状态。

我修改了您的app.js文件:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.bannerState = false;

  $scope.changeHeader = function () {
    $scope.bannerState = true;
  };

  $scope.currentImage = window.localStorage.getItem("bannerImage") | 0;

  $scope.nextButton = function () {
    if ($scope.bannerState) {
      $scope.currentImage++;
    }
    if ($scope.currentImage > ($scope.bannerImages.length - 1)) {
      $scope.currentImage = 0;
    }
  };

  $scope.previousButton = function () {
    if ($scope.bannerState) {
      $scope.currentImage--;
    }
    if ($scope.currentImage < 0) {
      $scope.currentImage = ($scope.bannerImages.length - 1);
    }
  };

  $scope.setHeader = function () {
    window.localStorage.setItem("bannerImage", $scope.currentImage);
    $scope.bannerState = false;
  };

  $scope.bannerImages = [
    {
      src: "http://yaocho-digital.com/portfolio/content/threadme1.png"
    },
    {
      src: "http://yaocho-digital.com/portfolio/content/threadme2.png"
    },
    {
      src: "http://yaocho-digital.com/portfolio/content/threadme3.png"
    }
  ];
});