1

I have a controller embedded using the ng-controller tag and it works fine but i've also got an external controller who needs to call one function of this controller:

<div ng-controller='NavigationController'>
    <!-- some html-->
</div>

And the controller

app.controller('NavigationController', function ($scope) {
  $scope.downloadItems = function(value) {
    //do something
  }
})

Now I want to trigger The downloadItems method from an other controller.

And I can't find it anywhere how this should be done?

1 Answer 1

3

I'm just learning Angular.js myself, but I'm pretty sure that if you want to reuse logic like this, you should put it into a service. (In fact, it's probably a good idea to put that sort of work into a service no matter what, so that is easy to separate from the controller for testing and reuse.)

app.factory("NavigationService", function() {
    return {
        downloadItems: function(value) { /* do something */ }
    }
});

app.controller("NavigationController", ["$scope", "NavigationService", function($scope, NavigationService) {
    $scope.downloadItems = function(value) {
        NavigationService.downloadItems(value);
    }
}]);

app.controller("OtherController", ["$scope", "NavigationService", function($scope, NavigationService) {
    ...
    NavigationService.downloadItems(value);
    ...
}]);

Now it's easy to test the download process outside the controller, and it's easy to mock the downloadItems function to test your controllers.

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

1 Comment

One note: I'm not yet sure if the correct format for explictly declaring injected services is to use the Array method I used above, or to use the $inject property, but either way, I think it's recommended if you ever plan to minify to do one of those.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.