AngularJS global controller AngularJS global controller angularjs angularjs

AngularJS global controller


There are a few different approaches I could recommend. First, even in a server side based MVC type application, this would not be a "global" controller, rather an Aspect Oriented service... or a "decorator". Angular is really no different in that regard, in that you have the ability to decorate your scope with the desired functionality. Your options here would be:

  • create a download directive
  • create a download provider/service/model
  • extend the scope with a decorator to add the method to all of your controllers

Depending on how you need to this functionality to be invoked, will determine your method of developing this feature. The most robust and portable, would be to create your own module, and register a provider that is a factory for this functionality. That would allow you to easily inject the functionality into any controller you choose, and configure some common settings across your module or application:

myApp.provider('download', function DownloadProvider() {  var configurableSetting = false;  this.setConfigurableSetting = function(value) {    configurableSetting = !!value;  };  this.$get = ["customArgument", function addDownload(customArgument) {    return new Download(customArgument, configurableSetting);  }];});function Download(customArgument, configurableSetting){  //download code  return {     addDownload:function(){        //code for method     }   }}

Then in your controller:

app.controller('whatever',['download',function(download){      var download1 = download(); //creates a new download instance      download.addDownload(); //executes method available on function}])

Using this pattern allows you to configure a provider for your newly created factory, so that you could set your configurableSetting during the config phase, easily adding common functionality across your module or application without having to explicitly define it in every call.

For more details on how this works, check out the Angular Developer guide on providers: http://docs.angularjs.org/guide/providers