[英]Angular.js callback from another controller
In my angular project I'm using Angular.js material . 在我的有角项目中,我正在使用Angular.js材质 。 And I want to show
$mdialog
with custom controller, where user changes some data and this data should be applied to my $scope
variable. 我想显示带有自定义控制器的
$mdialog
,其中用户更改了一些数据,并且该数据应应用于我的$scope
变量。 Example what I do now: 我现在做的例子:
function myControllerFn($scope, MyService){
// I do copy of my service variable because I don't want to change it until user will click save button
$scope.name = angular.copy(MyService.name);
$scope.editCurrentProfile = function() {
$scope.showEditProfileDialog($scope.name).then(function(name){
$scope.name = name;
}
}
$scope.showEditProfileDialog = function(name) {
var deferred = $q.defer();
$mdDialog.show({
controller: 'editProfileViewCtrl',
templateUrl: 'controllers/editProfileDialog.tmpl.html',
locals: {
name: name,
deferred: deferred
}
});
return deferred.promise;
};
}
Then in dialog controller I do: 然后在对话框控制器中执行以下操作:
function editProfileViewCtrl($scope, name, deffered) {
deferred.resolve('newName');
}
But I think it is the wrong way. 但是我认为这是错误的方法。 So what is the best way to communicate between two view controllers in angular without new service ?
那么,在没有新服务的情况下,两个视图控制器之间进行角度通信的最佳方法是什么? Or better create another service like:
EditDialogService
, where I will save results ? 或者更好地创建另一个服务,例如:
EditDialogService
,我将在其中保存结果?
When you open a modal, the show()
function returns a promise. 当您打开模态时,
show()
函数将返回promise。
$scope.showEditProfileDialog = function(name) {
var modalInstance = $mdDialog.show({
controller: 'editProfileViewCtrl',
templateUrl: 'controllers/editProfileDialog.tmpl.html',
locals: {
name: name
}
});
modalInstance.then(function(result){
// acces what is returned
// In your case, you would do
$scope.name = result;
}, function(error){
// Usually when you cancel your modal
});
}
Your modal controller can be injected with $mdDialog
. 您的模态控制器可以注入
$mdDialog
。
function editProfileViewCtrl($scope, name, $mdDialog) {
$scope.close = function() {
$mdDialog.hide('newName');
}
}
You should create a directive with your user as scope variable. 您应该使用用户作为范围变量来创建指令。 Angular in itself is handling the data binding.
Angular本身正在处理数据绑定。
It is possible to create a minimal controller function that has access to $scope. 可以创建一个可以访问$ scope的最小控制器功能。
$mdDialog.show({
controller: function () { this.parent = $scope; },
templateUrl: 'controllers/editProfileDialog.tmpl.html',
locals: {
name: name,
deferred: deferred
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.