chrissavage chrissavage - 4 months ago 33
AngularJS Question

Injecting Underscore.js into Angular Controller

I tried two of the solutions here to no avail.

This is my Error:

angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module flavorApplication due to:
Error: [$injector:unpr] Unknown provider: underscore


Here is my code for the module:



var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function() {
return $window._;
}]);





Here is my App Config:



(function(){
angular.module("flavorApplication",
['ui.bootstrap',
'ui.router',
'angular-loading-bar',
'angular-confirm',
]);
angular.module("flavorApplication").config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
'underscore', function ($stateProvider, $urlRouterProvider, $locationProvider, underscore){





Here I'm trying to inject it into a Controller (probably where I'm going wrong)



(function () {
'use strict';

angular
.module('flavorApplication')
.controller('UsedSearchesController', UsedSearchesController);

UsedSearchesController.$inject = ['$stateParams', '$state', 'DataService', '_'];
function UsedSearchesController($stateParams, $state, DataService, _) {
var vm = this;
vm.currentSearches = $stateParams.search.split("|")


activate(vm);

////////////////

function activate(vm, _) {
vm.removeSearch = function (searchTerm) {
$stateParams.search = _.filter(vm.currentSearches,
function(search){return search !== searchterm}).join("|")
$state.go('home');
}
}
}
})();




Answer

You missed $window dependency to inject in your factory

underscore.factory('_', ['$window', function($window) {

Other thing you can't get factory/service singleton object to be avail at config phase of angular, you can't get that object there.

//remove 'underscore' dependency from config phase like below.
angular.module("flavorApplication").config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
   function ($stateProvider, $urlRouterProvider, $locationProvider){

Additionally, you don't need to add _ as a parameter in activate function,

function activate(vm) { //<-- remove _ from here

Don't forget to inject underscore module to flavorApplication module so that would make available _ object throughout application modules & components.

angular.module("flavorApplication",
['ui.bootstrap',
    'ui.router',
    'angular-loading-bar',
    'angular-confirm',
    'underscore' //<-- added underscore module here
]);