Use underscore inside Angular controllers

前端 未结 6 1146
轮回少年
轮回少年 2020-11-30 16:16

How do I use underscore library inside angularjs controllers?

On this post: AngularJS limitTo by last 2 records somebody suggested to assign an _ variable to the ro

6条回答
  •  隐瞒了意图╮
    2020-11-30 17:03

    When you include Underscore, it attaches itself to the window object, and so is available globally.

    So you can use it from Angular code as-is.

    You can also wrap it up in a service or a factory, if you'd like it to be injected:

    var underscore = angular.module('underscore', []);
    underscore.factory('_', ['$window', function($window) {
      return $window._; // assumes underscore has already been loaded on the page
    }]);
    

    And then you can ask for the _ in your app's module:

    // Declare it as a dependency of your module
    var app = angular.module('app', ['underscore']);
    
    // And then inject it where you need it
    app.controller('Ctrl', function($scope, _) {
      // do stuff
    });
    

提交回复
热议问题