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

时间:2015-04-21 19:23:05

标签: angularjs

我有这种情况

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

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 () {

                });

        };

    }]);

假设我可以打开模态,我可以" SaveSomething"。

从ControllerTwo向ControllerOne发送一些数据需要做些什么?

我已查看过这篇文章Working with $scope.$emit and .$on 但我还没有解决问题。

观测值:

  • FileOne.js - >我有ControllerOne(parrent) - > $对
  • FileTwo.js - >我有ControllerTwo(孩子) - > $发射
  • 是的,我可以点击$ http.post.success条件
  • 中的代码

1 个答案:

答案 0 :(得分:5)

假设您正在使用angular-ui bootstrap(具有$ model),那么模型中的$ scope是$ rootScope的子视图。

根据$model documentation,您可以使用ControllerOne选项提供$scope 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()方法。