我有$scope.users
显示一些项目。
当我点击其中一个项目时,会出现一个模式以确认删除。
要删除的查询效果很好,但我的$scope.users
未在视图中更新...
我认为这是因为$scope.users
不是同一个控制器。
更新范围的解决方案是什么? (不使用$ 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');
};
}]);
答案 0 :(得分:2)
尝试:
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
范围内{$ 1}}的$ scope范围是子范围。分配backController
时,它会在子范围上创建新属性,而不更新父范围。当前解决方案从继承的属性中清除数据并向其添加新数据,以便更新父作用域。
范围 - 用于模态内容的范围实例(实际上 $ modal服务将创建一个提供的子范围 范围)。默认为$ rootScope
另一种解决方案是声明属性挂起您的数据:
$scope.users = data;
然后您可以在模态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
});
$scope.data.users = data;
注意:请记住更新模板绑定以添加此modalDeleteUserController
前缀。