简体   繁体   中英

Angular reload embedded controller

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM