Working with $ emit and $ on from child modal to parent angularjs

I have such a situation.

two files, both in one application

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

      

file one is the parent and I have:

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

}]);

      

file two is a child and I have:

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

                });

        };

    }]);

      

Assuming I can open the modal and I can "SaveSomething".

What do I need to do to send some data from ControllerTwo to ControllerOne?

I have already checked this post Working with $ scope. $ emit and. $ on but I can't solve the problem yet.

Obs:

  • FileOne.js -> I have ControllerOne (parrent) -> $ on
  • FileTwo.js -> I have ControllerTwo (child) -> $ emit
  • Yes, I can push the code inside the $ http.post.success condition
+3


source to share


1 answer


Assuming you are using angular-ui bootstrap (which has a $ model) then the $ scope in the model is a child of the $ rootScope.

According to the $ model documentation, you can provide ControllerOne

$scope

with an option scope

that will make the modal $scope

child of whatever you supply. Thus:

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

      



Then you can fix it using $scope.$parent.$emit(...)

. Strictly speaking, this creates a connection in the sense that it assumes that the user

modal is listening to events.

If you don't want to inject your scope, you can inject $rootScope

and emit it. But this will also dispatch an event to every area of ​​the application.

This assumes that you really want to leave the modal open and send a message back to the parent controller. Otherwise, use the methods close()

or dismiss()

.

+5


source







All Articles