对于添加新用户,我使用Angular Material(mdDialog
)使用对话框,但现在我必须刷新页面以添加新数据。
要获取用户,我在AdminController中使用此代码:
var init = function() {
$http({
method: 'GET',
url: 'http://localhost/hrm/public/getUsers'
}).success(function(data) {
angular.forEach(data, function(item) {
console.log(item);
$scope.users.push(item);
});
}).error(function (data) {
console.log(data);
});
};
init();
要添加用户,我在AdminController中使用此代码:
$scope.addUser = function(event) {
$mdDialog.show({
controller: DialogController,
parent: angular.element(document.body),
templateUrl: 'views/admin/addUser.html',
controllerAs: 'ctrl',
clickOutsideToClose: true,
targetEvent: event
}).then(function(addUser) {
$mdToast.show(
$mdToast.simple()
.textContent("User ajouté avec succès")
.position('top right')
.hideDelay(1500)
);
}, function(cancel) {
});
};
addUser我在DialogController中添加了这个函数:
$scope.addUser = function() {
if($scope.password == $scope.cpassword) {
$http({
method: 'POST',
url: 'http://localhost/hrm/public/saveUser',
data: {email: $scope.email,password: $scope.password}
}).success(function(data) {
$http({
method: 'POST',
url: 'http://localhost/hrm/public/assign-role',
data: {email: $scope.email, name: $scope.selectedItem}
}).success(function(data) {
$scope.users.push(data);
console.log(data);
});
});
} else {
console.log("password error");
}
$mdDialog.hide();
};
我收到此错误:
TypeError:无法读取属性' push'未定义的
我认为因为我将$scope.users = []
放在AdminController中,而没有在DialogController中访问。
那么如何在两个控制器中使用$scope.users
?
答案 0 :(得分:0)
有很多原因要做,例如在评论$rootScope
或locals
或$emit or $broadcast or $watch
所以我用$ mdDialog的locals属性解决了,所以在AdminController的$ scope.addUser中我确实喜欢这个
$scope.addUser = function (event) {
$mdDialog.show({
controller: DialogController,
parent: angular.element(document.body),
templateUrl: 'views/admin/addUser.html',
controllerAs: 'ctrl',
locals: {
items: $scope.users
},
clickOutsideToClose:true,
targetEvent: event
}).then(function (addUser) {
$mdToast.show(
$mdToast.simple()
.textContent("User ajouté avec succès")
.position('top right')
.hideDelay(1500)
);
}, function(cancel) {
});
};
并添加功能
$scope.addUser = function () {
if($scope.password == $scope.cpassword){
$http({
method: 'POST',
url: 'http://localhost/hrm/public/saveUser',
data: {email: $scope.email,password: $scope.password}
}).success(function (data) {
$http({
method: 'POST',
url: 'http://localhost/hrm/public/assign-role',
data: {email: $scope.email, name: $scope.selectedItem}
}).success(function (data) {
items.push(data);
});
});
}
else {
console.log("password error");
}
$mdDialog.hide();
};
并且items
必须传递控制器功能。