0

I'm new to angular and have to fix bugs of my collegue. I found this factory with functions. How can I put a reset_All-function that calls the reset-function of all modules ?

.factory('MyCollection', function() {
    return {

        resetAll: function(projectId) {

          // call the reset-function of SomeController

        }
    }
})



.controller('SomeController', function($scope, a) {


    $scope.reset = function() {
        ...........
    }

 }
0

2 Answers 2

2

If you want to prevent tight coupling of the different modules, you can broadcast an event and catch it in the respective controllers:

.factory('MyCollection', ['$rootScope', function($rootScope) {
    return {
        resetAll: function(projectId) {
            $rootScope.$broadcast('reset');
        }
    };
}]);

.controller('SomeController', ['$scope', 'a', function($scope, a) {
    $scope.reset = function() {
        // do something here
    }; 

    $scope.$on('reset', function() {
        $scope.reset();
    });
}]);

To learn about Angular's events have a look at Understanding Angular’s $scope and $rootScope event system $emit, $broadcast and $on

Sign up to request clarification or add additional context in comments.

Comments

2

You need to depend on MyCollection, so you can inject it:

.controller('SomeController', [ '$scope', 'a', 'MyCollection',
    function ($scope, a, MyCollection) {


    $scope.reset = function(id) {
        MyCollection.resetAll(id)
    }

 }]);

Here is the documentation to read.

2 Comments

Downvote reason: Does not answer the question, he wants to invoke $scope.reset from MyCollection, not the other way around.
Not to be "that guy" but your correction actually made it worse, you cannot inject a controller and 'MyCollection' is actually a factory. Dennis Traubs solution seem like the way to go for doing what the question was about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.