how to install underscore.js in my angular application?

左心房为你撑大大i 提交于 2019-12-03 13:56:50

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

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);
  });

Here's how you do it:link You basically need to add angular underscore module which acts as a bridge between the two.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!