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
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);
});
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);
});
链接地址: http://www.djcxy.com/p/77858.html
上一篇: 创建ac#函数来比较int结果