我想做一些类似的事情:
1. Set $scope.val = <Some dynamic data>
2. Click a link and be routed to a new template (with the same controller).
3. $scope.val should still be the same value as it was on the last page.
以某种方式持久保存范围内的数据是否是解决此问题的正确方法,或者还有其他方法吗?您甚至可以创建一个在路由之间具有持久作用域的 Controller ,当然除了将其保存在数据库中之外。
最佳答案
您可以在 Controller 之间共享数据,但不能使用简单的 $scope
。
您可以使用services对于这个任务。
每当您访问新路线时,都会重新创建 Controller 。但服务是应用程序中的单例。因此,可以从每个新 Controller 访问存储在服务中的数据。
您的服务可以非常简单,只返回一个空对象:
app.factory('sharedData', function() {
return {
name: 'Daniel'
};
});
然后在您的 Controller 中,您可以简单地将服务中的数据对象设置为 $scope
。
app.controller('MainController', function($scope, sharedData) {
$scope.data = sharedData;
});
这是一个工作 Plunker
关于AngularJS在路由之间传递范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31471440/