You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS跨HTML页面共享$scope.items数据问题求助

Fixing Empty $scope.items When Switching Pages in AngularJS cartController

Hey there, I’ve run into this exact issue a bunch of times with AngularJS—let’s break down what’s going on and fix it.

Why is $scope.items empty on the second page?

AngularJS controllers are tightly tied to their associated views. When you switch to a new HTML page, the original cartController instance gets destroyed, and a brand new instance spins up for the second page. Since $scope is scoped to the controller instance, your new $scope.items starts completely empty—none of the data from the first controller carries over automatically.

The Solution: Use a Singleton Service to Share Data

AngularJS services are singletons, meaning they only get created once and persist throughout your app’s lifecycle. We’ll use a service to store your cart data so it’s accessible across controllers and page switches.

Step 1: Create a Data Sharing Service

First, define a service to hold your cart items and provide methods to get/set the data (we’ll even add localStorage support to persist data across page refreshes):

angular.module('yourAppModule')
.factory('CartDataService', function() {
  // Initialize with saved data if available
  var storedItems = localStorage.getItem('cartItems');
  var items = storedItems ? JSON.parse(storedItems) : [];

  // Helper to save data to localStorage
  var saveToStorage = function() {
    localStorage.setItem('cartItems', JSON.stringify(items));
  };

  return {
    getItems: function() {
      return items;
    },
    setItems: function(newItems) {
      items = angular.copy(newItems); // Avoid reference bugs with angular.copy
      saveToStorage();
    }
  };
});

Step 2: Update the First Page’s Controller

When you load your JSON data in the first page’s cartController, save it to the service (not just $scope):

angular.module('yourAppModule')
.controller('cartController', function($scope, $http, CartDataService) {
  $scope.loadItems = function() {
    $http.get('your-json-data-url.json')
      .then(function(response) {
        $scope.items = response.data;
        // Save loaded data to the singleton service
        CartDataService.setItems(response.data);
      })
      .catch(function(error) {
        console.error('Failed to load items:', error);
      });
  };
});

Step 3: Retrieve Data in the Second Page’s Controller

In the second page’s controller (even if it’s the same cartController), pull the data from the service into the local $scope:

angular.module('yourAppModule')
.controller('cartController', function($scope, CartDataService) {
  // Fetch saved items from the service
  $scope.items = CartDataService.getItems();

  // Optional: Add a fallback message if data is empty
  if ($scope.items.length === 0) {
    $scope.emptyMessage = "No items found. Head back to the first page to load data.";
  }
});

Bonus: Skip LocalStorage if You Don’t Need Persistence

If you don’t need data to survive page refreshes, you can strip out the localStorage code and just keep the in-memory array in the service—it’ll still work across page switches as long as the app doesn’t fully reload.

That’s it! Your cart data will now stay accessible across page switches because it’s stored in a singleton service instead of a controller-specific $scope.

内容的提问来源于stack exchange,提问作者janusz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:10:19