2016-07-26 37 views
0

我正在使用一個靜態json文件來模擬我的服務器並從中獲取我的一系列命令。 我在我的html文件中的表格中顯示訂單,並從中刪除一個訂單。 每次我加載html文件時,完整列表都會被加載,並且我已經通過控制器功能刪除了這些命令。Angular JS:我怎樣才能加載工廠一次?

我怎樣才能從工廠只有一次數據?

這裏是我的控制器:

app.controller("MainPageCtrl", function($scope, getOrdersFactory) 
{ 
    $scope.orders = []; 
    // Getting the data frm the facrory 
    var dataPromise = getOrdersFactory.getDataFunc(); 
    dataPromise.then(function(data){ 
      $scope.orders = data.orders; 
    }); 

    // Deletes an orders. 
    $scope.deleteOrder = function(order){ 
    // Finds the index of the order. 
    var orderIndex = $scope.orders.indexOf(order); 

    // Delete the order. 
    $scope.orders.splice(orderIndex, 1); 
    }; 
}); 
+0

你到底是什麼意思?一旦進入......什麼?你想在瀏覽器緩存中存儲一​​些數據嗎? – k102

+0

請參閱http://stackoverflow.com/questions/22182730/angularjs-service-only-running-the-first-time-controller-is-used。 – Ioan

回答

0

默認情況下角服務和工廠都是單身(只加載一次)。您面臨的問題是控制器重新初始化。當路線發生變化時,控制器會重新初始化,以便從工廠獲取以前的值。

您可以在'getOrdersFactory'上使用setter函數。

假設你的「getOrdersFactory」是

app.factory('getOrdersFactory',function(){ 
//code to read from file and set the file on a variable orderDetails 
var orderDetails = contentsReadFromFile; 
return{ 
    getDataFunc:function(){ 
    return orderDetails 
    }, 
    setDataFunc:function(modifiedOrderDetails){ 
    orderDetails = modifiedOrderDetails; 
    //code to set the new content to the static file 
    } 
} 
} 

代碼來讀取靜態文件的文件時,你注入工廠首次設置上將會呈現,並控制器上的訂單詳情刪除功能

// Deletes an orders. 
$scope.deleteOrder = function(order){ 
// Finds the index of the order. 
var orderIndex = $scope.orders.indexOf(order); 

// Delete the order. 
$scope.orders.splice(orderIndex, 1); 
getOrdersFactory.setDataFunc($scope.orders); 
}; 
0

我猜你失去你的數據,即$ scope.orders。如果這是該方案只是改變

dataPromise.then(function(data){ 
      $scope.orders = data.orders; 
    }); 

dataPromise.then(function(data){ 
      $scope.orders = angular.copy(data.orders); 
    });