简体   繁体   中英

AngularJS: How to inject underscore into controller without factory

please guide me How can i inject underscore into controller without factory.

with factory my code example is running....here it is.

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

myApp.factory('_', function() {
  return window._; //Underscore should be loaded on the page
});


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

});   

but without factory when i try to inject underscore in controller then getting error as follows

SyntaxError: missing ) after argument list Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

here is the code without factory injecting underscore into controllers.

<div ng-app="myApp" ng-controller="MainCtrl">

</div>

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

myApp.controller('MyCtrl', function ($scope, _) 
{
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS2',
      'AngularJS1'
    ];

    var x = _.last($scope.awesomeThings, 2);
    _.each(x.reverse(), alert);    
});

i am missing something....please tell me what i need to rectify in code. thanks

you can create a separate module for underscore like this

var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
  return $window._; // assumes underscore has already been loaded on the page
}]);

Now inject the underscore module to your app module

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

myApp.controller('MyCtrl', function ($scope, _) 
{
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS2',
      'AngularJS1'
    ];

    var x = _.last($scope.awesomeThings, 2);
    _.each(x.reverse(), alert);    
});

dependency injection should only be used for angular stuff (services, controllers,...).

Everything that is not related to angular is not supposed to be used with dependency injection.

As far as underscore is loaded before your angular controller, you can use it as it will be added to the window object.

The following will work without any problem :

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

myApp.controller('MyCtrl', function ($scope) 
{
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS2',
      'AngularJS1'
    ];

    var x = _.last($scope.awesomeThings, 2);
    _.each(x.reverse(), alert);    
});

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