简体   繁体   中英

AngularJS, RequireJS and Vanilla Javascript Functions

default-functions.js

function width(){
    console.log($(window).width());
}

If I have a function - like the one above.

I don't want to add it into each controller in an AngularJS application but because I'm using RequireJS too I want the function to flow through the app without having to repeatedly add that snippet of code or any reference to that snippet on each controller.

Would there be a way to add it into the application when bootstrapped?

At the moment I have the following layout.

main.js

requirejs([ 'vendors/jquery.min',
        'angular',
        'app',
        'routes',
        'ui-bootstrap',
        'default-functions',
        'services/services',
        'directives/directives',
        'filters/filters',
        'controllers/controllers'
       ], function ($, angular, app, _) {
           angular.element(document).ready(function () {
               angular.bootstrap(document, ['App']);
               document.getElementsByTagName('html')[0].dataset.ngApp = 'App';
           });

       });

controller.js

define([], function() {

    var Ctrl = function( $scope, $timeout, $http, $routeParams, $rootScope) {
        width();
    }
    return Ctrl
});

At the moment the application returns width is not defined - is there anyway I can get each function I may add into default-functions.js to get defined without adding each into each controller like you would with a Service .

What you want to do is considered a bad practice. Having those generic functions defined in the global namespace is not a good idea and defeats the purpose of Dependency Injection. Doing that would make your code much more difficult to test and maintain.

I suggest that you create a Utils service like this:

app.service('utils', function(){
 return {
    width: function(){ /*do something here*/ },
    anotherUtilFunction:  function(){ /* do something else here*/ }
    /*as many more functions as you want here*/
 };
})

And then in your controller just do this:

var Ctrl = function( $scope, $timeout, $http, $routeParams, $rootScope, utils) {
    utils.width();
    utils.anotherUtilFunction();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM