我有 $scope.users
显示一些项目。
当我单击其中一项时,会出现一个确认删除的模式。
删除查询效果很好,但我的 $scope.users
没有在 View 中更新...
我认为这是因为 $scope.users
不是同一个 Controller 。
更新范围的解决方案是什么? (不使用 $rootscope)?
app.controller('backController', ['$scope', '$http', '$rootScope','MyFunctions', '$location', '$modal',
function ($scope, $http, $rootScope, MyFunctions, $location, $modal) {
MyFunctions.getUsers().then(function (data) {
$scope.users = data;
});
$scope.openModalDeleteUser = function (user) {
$scope.user = user;
var modalInstance = $modal.open({
templateUrl: 'template/app/modalDeleteUser.html',
controller: 'modalDeleteUserController',
scope: $scope,
});
};
}]);
app.controller('modalDeleteUserController', ['$scope', '$modalInstance', 'MyFunctions',
function ($scope, $modalInstance, MyFunctions) {
$scope.delete = function(){
var data = {};
data['action'] = 'delete_user';
MyFunctions.updateData(data).then(function (response){
MyFunctions.getUsers().then(function (data) {
$scope.users = data;
console.log($scope.users); // Data retrieve is OK, but not updated in the view
});
});
$modalInstance.dismiss('cancel');
}
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
最佳答案
尝试:
MyFunctions.getUsers().then(function (data) {
$scope.users.length = 0; //empty the current array
$scope.users.push.apply($scope.users,data); //push the data array to current array.
});
说明:
modalDeleteUserController
中的 $scope 是 backController
范围的子范围。当您分配 $scope.users = data;
时,它会在子作用域上创建一个新属性,而无需更新父作用域。当前的解决方案清除继承属性中的数据并向其中添加新数据,以便更新父范围。
来自documentation :
scope - a scope instance to be used for the modal's content (actually the $modal service is going to create a child scope of a provided scope). Defaults to $rootScope
另一个解决方案是声明一个属性来挂起您的数据:
app.controller('backController', ['$scope', '$http', '$rootScope','MyFunctions', '$location', '$modal',
function ($scope, $http, $rootScope, MyFunctions, $location, $modal) {
$scope.data = {};//declare a property
MyFunctions.getUsers().then(function (data) {
$scope.data.users = data; //store users as a property of this property
});
然后你可以在模态 modalDeleteUserController
中使用 $scope.data.users = data;
注意:请记住更新您的模板绑定(bind)以添加此 .data
前缀。
关于javascript - 如何在 AngularJS 模式 Bootstrap 之外更新 $scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24244719/