Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to install underscore.js in my angular application?

I used yo-angular to generate my angularjs template with bootstrap/grunt/bower. I also want to use underscore in the app:

npm install underscore --save-dev

In the MainCtrl I am calling underscore.js just to see whether it works:

angular.module('yomanApp')
  .controller('MainCtrl', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'AngularJS'
    ];

    _.each([1,2,3],console.log);
  });

When I run the application with Chrome I get this errmsg in the console:

ReferenceError: _ is not defined
    at new <anonymous> (http://localhost:9000/scripts/controllers/main.js:18:5)
    at invoke (http://localhost:9000/bower_components/angular/angular.js:4203:17)
    at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:4211:27)
    at http://localhost:9000/bower_components/angular/angular.js:8501:28
    at link (http://localhost:9000/bower_components/angular-route/angular-route.js:975:26)
    at invokeLinkFn (http://localhost:9000/bower_components/angular/angular.js:8258:9)
    at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7768:11)
    at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7117:13)
    at publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:6996:30)
    at $get.boundTranscludeFn (http://localhost:9000/bower_components/angular/angular.js:7135:16) <div ng-view="" class="ng-scope">

After this error I added the module to the app config: 'use strict';

/**
 * @ngdoc overview
 * @name yomanApp
 * @description
 * # yomanApp
 *
 * Main module of the application.
 */
angular
  .module('yomanApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'underscore'

  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      })
      .when('/accordeon', {
        templateUrl: 'views/accordeon.html',
        controller: 'IssuesCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

Now I am getting this error:

Uncaught Error: [$injector:modulerr] Failed to instantiate module yomanApp due to:
Error: [$injector:modulerr] Failed to instantiate module underscore due to:
Error: [$injector:nomod] Module 'underscore' 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.

Last thing I tried was adding it to the index.html:

<script src="node_modules/underscore/underscore.js"></script>

This results in the same error as above. Also get a 404 for the underscore.js?? Is this a grunt configuration issue or anything else?

like image 473
Pindakaas Avatar asked Apr 21 '15 09:04

Pindakaas


People also ask

What does underscore mean in Angularjs?

Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

How do I use underscore in Angularjs 6?

import { _ } from 'underscore'; Put above line of code inside component which component you want to use underscore js.

What is NPM underscore?

Underscore. js is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) without extending any core JavaScript objects. For Docs, License, Tests, and pre-packed downloads, see: https://underscorejs.org.

How do you install underscore module globally using node js?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.


2 Answers

I tend to just use a constant for this type of thing. It's a simple approach and allows you to explicitly state your dependencies in your application.

Install with bower:

bower install underscore --save

Load the library before angular:

<script src="bower_components/underscore/underscore.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="app/scripts/app.js"></script>

Define it as a constant (in app/scripts/app.js for example):

application.constant('_',
    window._
);

Then in your controllers/services:

application.controller('Ctrl', function($scope, _) {
    //Use underscore here like any other angular dependency
    var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
    $scope.names = _.pluck(stooges, 'name');
});
like image 112
djskinner Avatar answered Oct 16 '22 23:10

djskinner


Create a module with the name of underscore a module and then you can pass it in your application and it will be accessible. Currently the underscore module is undefined and hence you are getting this errror.

Your app becomes like this:

    var underscore = angular.module('underscore', []);
        underscore.factory('_', function() {
            return window._; //Underscore should be loaded on the page
        });

       angular
      .module('yomanApp', [
        'ngAnimate',
        'ngCookies',
        'ngResource',
        'ngRoute',
        'ngSanitize',
        'ngTouch',
        'underscore'

      ])
      .config(function ($routeProvider) {
        $routeProvider
          .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
          })
          .when('/about', {
            templateUrl: 'views/about.html',
            controller: 'AboutCtrl'
          })
          .when('/accordeon', {
            templateUrl: 'views/accordeon.html',
            controller: 'IssuesCtrl'
          })
          .otherwise({
            redirectTo: '/'
          });
      })
.controller('MainCtrl', function ($scope, _) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'AngularJS'
    ];

    _.each([1,2,3],console.log);
  });
like image 36
Jayram Avatar answered Oct 16 '22 23:10

Jayram