chrissavage chrissavage - 1 year ago 139
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:

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';

.controller('UsedSearchesController', UsedSearchesController);

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



function activate(vm, _) {
vm.removeSearch = function (searchTerm) {
$ = _.filter(vm.currentSearches,
function(search){return search !== searchterm}).join("|")

Answer Source

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.

    'underscore' //<-- added underscore module here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download