我有一个页面,可以显示数据库中的所有人员,我们将其称为所有人员页面。在该页面上我有两个选项:
- 添加新人
- 删除人员(无论我想要什么人员)
当我导航到另一个页面然后返回“所有人”页面时,会出现此问题。
如果我删除一个人,然后添加一个新人, View 将显示添加的新人,但也会显示已删除的人。
In the controller I am adding the data from the DB in an array.
$scope.persons_array = []
And display in the view via ng-repeat.
<div ng-repeat="(key, value) in persons_array)">
To Add a Person I am inserting a new ID in the array:
$scope.persons_array.push($scope.id[i])
To Delete a Person I am removing the spcified ID from the array:
$scope.persons_array.splice(i,1);
测试:
To discover what the problem is I've created an setInterval function:
setInterval(function(){
console.log($scope.persons_array)
}, 5000)
When I was on the All Persons Page, where I already had a Person added, I could see:
[Object { id=667, $$hashKey="object:71"}]
When I navigate to another page and then get back:
[Object { id=667, $$hashKey="object:71"}] //original
[Object { id=667, $$hashKey="object:220"}] //new
Add a New Person:
[Object { id=667, $$hashKey="object:71"}] //original
[Object { id=667, $$hashKey="object:220"}, Object { id=668, $$hashKey="object:227"}] //new
Detele the Person just added:
[Object { id=667, $$hashKey="object:71"}] //original
[Object { id=667, $$hashKey="object:220"}, Object { id=668, $$hashKey="object:227"}] //new
Delete the Person that was already in the DB:
[] //original
[Object { id=667, $$hashKey="object:220"}, Object { id=668, $$hashKey="object:227"}] //new
Add Again a New Person:
[] //original
[Object { id=667, $$hashKey="object:220"},
Object { id=668, $$hashKey="object:227"},
Object { id=669, $$hashKey="object:235"}] //new
据我所知,在我导航到另一个页面时,Angular 正在以某种方式复制 $scope.persons_array,之后不再更新原始数组。
最佳答案
Controller 不会在路由更改时自动释放,因此您在其中创建的 setInterval 会一直使用 Controller 的特定实例当时手头上的任何数据愉快地不断地循环,即使在您离开正在使用它的路由之后也是如此.
当 Controller 不再附加到事件元素时,Angular 会发送 $destroy
事件;在 Controller 中监视该事件并取消绑定(bind)任何正在进行的函数(例如 setInterval
)。
$scope.intervalID = setInterval(function(){
console.log($scope.persons_array)
}, 5000);
$scope.on('$destroy', function() {
clearInterval($scope.intervalID);
// and remove any other data that you don't need persisting
});
如果您在 Controller 范围内存储大量内容,这可能会变得非常麻烦。就我个人而言,我倾向于仅使用 Controller 作为幂等函数的容器,而是将数据存储在指令上(如果它是特定于实例的)或服务中(如果需要在应用程序之间共享)——这解决了上述问题,并且还有助于避免使用同一 Controller 的指令之间的范围泄漏。
关于javascript - 导航到另一个页面时,Angular 会复制 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44050931/