Make a function available in every controller in angular
You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:
<!doctype html> <html ng-app="myApp"> <head> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script> <script type="text/javascript"> var myApp = angular.module('myApp', []); myApp.factory('myService', function() { return { foo: function() { alert("I'm foo!"); } }; }); myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) { $scope.callFoo = function() { myService.foo(); } }]); </script> </head> <body ng-controller="MainCtrl"> <button ng-click="callFoo()">Call foo</button> </body> </html>
If that's not an option for you, you can add it to the root scope like this:
That way, all of your templates can call<!doctype html> <html ng-app="myApp"> <head> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script> <script type="text/javascript"> var myApp = angular.module('myApp', []); myApp.run(function($rootScope) { $rootScope.globalFoo = function() { alert("I'm global foo!"); }; }); myApp.controller('MainCtrl', ['$scope', function($scope){ }]); </script> </head> <body ng-controller="MainCtrl"> <button ng-click="globalFoo()">Call global foo</button> </body> </html>
globalFoo()
without having to pass it to the template from the controller.
0 nhận xét:
Đăng nhận xét