gpt4 book ai didi

javascript - 添加或删除数据后 Angular 页面不刷新

转载 作者:行者123 更新时间:2023-11-29 18:17:34 25 4
gpt4 key购买 nike

我的 Angular 应用程序经常出现问题,在添加、编辑或删除数据后它不会刷新页面。因此,如果我将新项目添加到主题列表中,新项目不会出现在列表中,除非我离开该页面然后返回到该页面。我试过使用 route.reload 然后重置下面主题列表的范围。我发出警报以查看它是否被触发 - 但警报出现在页面重定向回主题列表之前,这很奇怪,因为 $location.path('/subjects') 在它之前有两行。这是我的 Controller :

angular.module('myApp.controllers')
.controller('SubjectEditCtrl', ['$scope', '$routeParams', 'SubjectFactory', 'SubjectsFactory', '$location', '$route',
function ($scope, $routeParams, SubjectFactory, SubjectsFactory, $location, $route) {

// callback for ng-click 'updateSubject':

$scope.updateSubject = function () {

//Performs an update to the server
SubjectFactory.update($scope.subject);
//Redirects to list of all subjects
$location.path('/subjects/');
//Should reset the scope of the subject list
$scope.subjects = SubjectsFactory.query();
//Should reload the page
$route.reload();
//For debugging- the alert appears BEFORE the redirect to list of all subjects happens
alert('route reload happening');
};


SubjectFactory.show({id: $routeParams.subjectId}).$promise.then(function(subject) {
$scope.subject = subject;
}, function(err) {
console.error(err);
});


}]);

谁能提出解决方案?

编辑:主题服务

var app = angular.module('myApp.services');

app.factory('SubjectsFactory', function ($resource) {
return $resource('https://myapiurl.com/subjects', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
});

app.factory('SubjectFactory', function ($resource) {
return $resource('https://myapiurl.com/subjects/:id', {}, {
show: { method: 'GET', isArray: false },
update: { method: 'PATCH', params: {id: '@id'} },
delete: { method: 'DELETE', params: {id: '@id'} }
})
});

最佳答案

有时您需要将更改应用于范围,这是通过以下代码完成的:

$scope.$apply();

但这只有在不在“$digest”阶段才能进行,否则会抛出异常。所以你需要首先检查它不在“$digest”阶段然后你可以应用它。以下是我用于安全应用更改的代码示例:

safeApply: function (scope, callback) {
if (scope.$$phase != '$apply' && scope.$$phase != '$digest' &&
(!scope.$root || (scope.$root.$$phase != '$apply' && scope.$root.$$phase != '$digest'))) {
scope.$apply();
}
if (angular.isFunction(callback)) {
callback();
}
}

关于javascript - 添加或删除数据后 Angular 页面不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21699271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com