javascript – What is the best way to reuse codes between modules

Question:

I'm developing a tool using AngularJS, but I'm constantly getting hit by it, I need to reuse code from different modules and files, but it's not working properly. With pure javascript, it's ok to reuse other functions, even in different files, they "see themselves", but with angularJs it's not quite like that, I thought it was something like JAVA, where you need to import the class and create an instance, but also I can see that it's not that way, could someone show me an example of reusing functions in different modules and files in AngularJS?

Answer:

Basically there are two ways, defining it as a service or putting it in your root scope. The ideal is to create a service so as not to pollute your "root" scope. You can 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 it doesn't, you can add us my root scope 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.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>

That way all your templates can call globalFoot() without having to pass it to the controller template.

Source: https://stackoverflow.com/questions/15025979/can-i-make-a-function-available-in-every-controller-in-angular

Scroll to Top
AllEscort