2016-07-26 53 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); 
    });