AngularJS Global Controller

In my Angular application, I have several functions that I think should be in the global controller. In server-side MVC infrastructures, there is usually a global controller that all other controllers extend, and that is where I would put these functions. I am wondering if there is anything like this for Angular.

So, at the moment I have this in app.js:

'use strict';

// Declare app level module
var app = angular.module('app', ['ngRoute']).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

    // Possible routes can go here

}]);

And this is in controllers.js:

app.controller('DownloadsController', function ($scope) {

});

I want to be able to add downloads to my application, so I’ll write $scope.addDownload = function() { ... }to DownloadsController. This will work, however, I would like to be able to add downloads anywhere in my application, which means calling this function addDownload()no matter which controller I enter.

, addDownload() ?

+4
1

, . -, MVC "" , ... "". Angular , . :

  • / /
  • , .

, , . , factory . :

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
     }
   }
}

:

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

}])

, factory, configurableSetting , , .

, , . Angular : http://docs.angularjs.org/guide/providers

+10

Source: https://habr.com/ru/post/1536510/


All Articles