【问题标题】:how to install underscore.js in my angular application?如何在我的 Angular 应用程序中安装 underscore.js?
【发布时间】:2015-06-28 08:47:34
【问题描述】:

我使用 yo-angular 通过 bootstrap/grunt/bower 生成我的 angularjs 模板。我还想在应用中使用下划线:

npm install underscore --save-dev

在 MainCtrl 中我调用 underscore.js 只是为了看看它是否有效:

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

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

当我使用 Chrome 运行应用程序时,我会在控制台中看到这个 errmsg:

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">

在此错误之后,我将模块添加到应用程序配置中: '使用严格';

/**
 * @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: '/'
      });
  });

现在我收到此错误:

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.

我尝试的最后一件事是将它添加到 index.html:

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

这会导致与上述相同的错误。还为 underscore.js 获得 404?这是一个繁琐的配置问题还是其他什么?

【问题讨论】:

  • 如果你是通过npm install underscore --save-dev 安装的,那么你需要使用 Browserify 之类的东西才能在浏览器中使用它。如果您不想这样做,那么您需要通过 bower 安装并在您的 html 中包含 script 标签,然后再包含 angular。同时删除--save-dev 标志,而只使用--save,因为它不是开发依赖项。

标签: angularjs gruntjs npm underscore.js bower


【解决方案1】:

创建一个名为underscore的模块,然后你可以在你的应用程序中传递它,它就可以访问了。目前下划线模块未定义,因此您收到此错误。

你的应用变成这样:

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

【讨论】:

  • djskinner 的回答对我不起作用。正如您在此处提到的,它需要一个模块。感谢分享@Jayram
【解决方案2】:

我倾向于只使用常量来处理这类事情。这是一种简单的方法,允许您在应用程序中明确声明依赖项。

使用凉亭安装:

bower install underscore --save

在 angular 之前加载库:

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

将其定义为常量(例如app/scripts/app.js):

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

然后在您的控制器/服务中:

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

【讨论】:

  • 除了创建更明确的代码之外,是否有特定的理由将其声明为常量并将其注入我需要的地方?只需加载库,我就可以在全局范围内使用它。
  • 明确您的依赖关系并避免在整个代码中散布对全局对象的引用当然是一个好习惯,但正如您指出的那样,在这种情况下没有必要,因为它在window 上可用。有些人可能会争辩说,为一个无处不在的实用程序库(如下划线)声明一个常量的情况更小。就个人而言,我建议养成清楚地声明依赖关系的习惯。
【解决方案3】:

这是你的做法:link 您基本上需要添加角度下划线模块,作为两者之间的桥梁。

【讨论】:

  • 链接已失效。最好发布答案而不是链接到答案。
猜你喜欢
  • 1970-01-01
  • 2022-08-09
  • 2022-01-18
  • 1970-01-01
  • 2018-11-15
  • 1970-01-01
  • 2023-02-19
  • 1970-01-01
  • 2016-03-27
相关资源
最近更新 更多