在AngularJS中从子模态框使用$emit和$on与父元素交互

28 浏览
0 Comments

在AngularJS中从子模态框使用$emit和$on与父元素交互

我有这个情况:

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

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"
            }
        }
    });
}
}]);

文件二是子文件,我有:

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 () {
                });
        };
    }]);

假设我能打开模态框并“保存一些东西”。

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

我已经检查过这篇帖子:Working with $scope.$emit and .$on,但我还不能解决问题。

注:

  • FileOne.js - 我有ControllerOne(父级) - $on
  • FileTwo.js - 我有ControllerTwo(子级) - $emit
  • 是的,我可以在$http.post.success条件中执行代码
admin 更改状态以发布 2023年5月24日
0
0 Comments

假设您在使用angular-ui Bootstrap(该库提供了$model),那么模型中的$scope是$rootScope的子作用域。

根据$model文档,您可以通过使用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会听取此事件。

如果您不想注入您的作用域,则可以注入$rootScope,并在其中发送信号。但这也会将事件发送到应用程序中的每个作用域。

这是假设您实际上想让模态框保持打开状态并向父控制器发送消息。否则,请使用close()dismiss()方法。

0