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

Ionic中向$localStorage数组追加对象报错:push不是函数

Fixing "TypeError: $scope.sTempLoc.push is not a function" in AngularJS with $localStorage

Let's break down why this error is happening and fix it step by step—this is a common issue when working with arrays and $localStorage in AngularJS.

The error tells us directly: $scope.sTempLoc isn't an array when you try to call push() on it. Let's fix that and make sure we append objects without overwriting existing data.

1. Correctly Initialize Your Array

Right now, you're resetting $scope.sTempLoc = []; every time your saveWfhLocation function runs, which wipes out any existing data. Worse, if you're pulling data from $localStorage later and that data isn't properly parsed as an array, you'll end up with a non-array value that can't use push().

Instead, initialize the array once when the controller loads, pulling from $localStorage first (or defaulting to an empty array):

// Initialize when the controller loads, not inside the save function
$scope.sTempLoc = JSON.parse($localStorage.savedWfhLocations) || [];
  • JSON.parse() converts the string stored in $localStorage back to a JavaScript array (since $localStorage only stores strings).
  • The || [] ensures we get a clean empty array if there's no existing data in $localStorage.

2. Append the Object & Persist to $localStorage

Now inside your saveWfhLocation function, you can safely append your location object and save the updated array back to $localStorage:

$scope.saveWfhLocation = function (){
    // Build your location object from your current details
    const newWfhLocation = {
        uCuWfhLocNam: $scope.uCurLocDtls.uCuWfhLocNam,
        // Add any other properties you need here (e.g., coordinates, timestamps)
    };

    // Append the new object to the array (this will work now that sTempLoc is an array!)
    $scope.sTempLoc.push(newWfhLocation);

    // Save the updated array back to $localStorage (convert to string first)
    $localStorage.savedWfhLocations = JSON.stringify($scope.sTempLoc);

    // Optional: Add success feedback or navigation logic here
    $ionicPopup.alert({
        title: 'Success',
        template: 'Location saved!'
    });
};

3. Double-Check for Common Mistakes

If you still run into issues, verify these points:

  • Never store a single object directly in $localStorage.savedWfhLocations—always store the full array.
  • Make sure you aren't overwriting $scope.sTempLoc with a non-array value elsewhere in your code.
  • Confirm that any existing data in $localStorage is valid JSON (you can check this in your browser's dev tools under Application > Local Storage).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:23:12