gpt4 book ai didi

angularjs - 使用 $emit 和 $on 从子模态到父 angularjs

转载 作者:行者123 更新时间:2023-12-01 11:33:40 25 4
gpt4 key购买 nike

我有这种情况

两个文件,都在同一个应用程序中

var app = angular.module('myapp');

文件一是父级,我有:

app.controller("ControllerOne", ['$scope', '$http', '$modal', 
function ($scope, $http, $modal) {


$scope.$on('refreshList', function (event, data) {
console.log(data);
});

$scope.openModal = function () {

var modalInstance = $modal.open({
templateUrl: '/SomeFolder/FileWithControllerTwo',
controller: 'ControllerTwo',
size: 'lg',
resolve: {
someParam: function () {
return "param"
}
}
});
}

}]);

文件二是 child ,我有:

app.controller("ControllerTwo", ['$scope', '$http', 'someParam',
function ($scope, $http, someParam) {


$scope.SaveSomething = function () {

$http.post(url, obj)
.success(function (data) {

$scope.$emit('refreshList', [1,2,3]);

}).error(function () {

});

};

}]);

假设我可以打开模式并且我可以“SaveSomething”。

我需要做什么才能将一些数据从 ControllerTwo 发送到 ControllerOne?

我已经查看了这篇文章 Working with $scope.$emit and .$on但我还不能解决问题。

观测:

  • FileOne.js -> 我有 ControllerOne (parrent) -> $on
  • FileTwo.js -> 我有 ControllerTwo(子) -> $emit
  • 是的,我可以点击$http.post.success条件里面的代码

最佳答案

假设您正在使用 angular-ui bootstrap(它有一个 $model),那么模型中的 $scope 是 $rootScope 的子作用域。

根据 $model documentation您可以使用 scope 选项提供 ControllerOne $scope ,这将使模态的 $scope 成为无论你供应什么。因此:

var modalInstance = $modal.open({
templateUrl: '/SomeFolder/FileWithControllerTwo',
controller: 'ControllerTwo',
size: 'lg',
scope: $scope,
resolve: {
someParam: function () {
return "param"
}
}
});

然后您可以使用 $scope.$parent.$emit(...) 向其发出信号。严格来说,这会创建一个耦合,因为它假定模态的 user 会监听事件。

如果你不想注入(inject)你的作用域,你可以注入(inject) $rootScope 并在其上发射。但这也会将事件发送到应用程序中的每个范围。

这是假设您确实想要打开模式并将消息发送回父 Controller 。否则,只需使用 close()dismiss() 方法即可。

关于angularjs - 使用 $emit 和 $on 从子模态到父 angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29781314/

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