Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the ad-inserter domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/vhosts/blog.webeats.it/httpdocs/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the cookie-law-info domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/vhosts/blog.webeats.it/httpdocs/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the wordpress-seo domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/vhosts/blog.webeats.it/httpdocs/wp-includes/functions.php on line 6114
AngularJS creare una funzione disponibile in tutti i controller

Come creare una funzione disponibile in tutti i controller creando un servizio o inserendola nel root scope

Abbiamo 2 scelte per poter creare una funzione “globale” e quindi una funzione disponibile in tutti i controller:
1) Creare un servizio
2) Oppure inserirla nel root scope

Per evitare di “inquinare” il root scope, seguiremo quindi la prima strada.

Creiamo il servizio con .factory nel seguente modo:

var myApp = angular.module('myApp', []);

myApp.factory('mioServizio', function() {
   return {
      miaFunzione: function() {
         alert("Servizio di prova!");
      }
   };
});

Ora impostiamo il controller in modo che possa chiamare il servizio mioServizio:

myApp.controller('MainCtrl', ['$scope', 'mioServizio', function($scope, mioServizio) {
   $scope.chiamaServizio = function() {
      mioServizio.miaFunzione();
   }
}]);

Ora nella view

<!doctype html>
Chiama funzione globale

Mentre volendo utilizzare il metodo del root scope

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
   $rootScope.globalFoo = function() {
      alert("I'm global foo!");
   };
});

myApp.controller('MainCtrl', ['$scope', function($scope){

}]);
funzione disponibile in tutti i controller
funzione disponibile in tutti i controller