angularjs - 将 Underscore.js 注入(inject) Angular Controller

标签 angularjs underscore.js angular-controller

我尝试了两种解决方案 here没有效果。

这是我的错误:

angular.js:68 未捕获错误:[$injector:modulerr] 无法实例化模块flavorApplication,原因是: 错误:[$injector:unpr] 未知提供者:下划线

这是我的模块代码:

var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function() {
  return $window._;
}]);

这是我的应用程序配置:

(function(){
  angular.module("flavorApplication",
    ['ui.bootstrap',
        'ui.router',
        'angular-loading-bar',
        'angular-confirm',
        ]);
        angular.module("flavorApplication").config(['$stateProvider', '$urlRouterProvider', '$locationProvider', 
        'underscore', function ($stateProvider, $urlRouterProvider, $locationProvider, underscore){

这里我试图将它注入(inject)到 Controller 中(可能是我出错的地方)

(function () {
    'use strict';

    angular
        .module('flavorApplication')
        .controller('UsedSearchesController', UsedSearchesController);

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


        activate(vm);

        ////////////////

        function activate(vm, _) {
            vm.removeSearch = function (searchTerm) {
              $stateParams.search =  _.filter(vm.currentSearches, 
              function(search){return search !== searchterm}).join("|")
                $state.go('home');
            }
        }
    }
})();

最佳答案

您错过了在工厂中注入(inject)的 $window 依赖项

underscore.factory('_', ['$window', function($window) {

其他你无法在 Angular 的配置阶段使用 factory/service 单例对象,你无法在那里获取该对象。

//remove 'underscore' dependency from config phase like below.
angular.module("flavorApplication").config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
   function ($stateProvider, $urlRouterProvider, $locationProvider){

此外,您不需要在activate函数中添加_作为参数,

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.

angular.module("flavorApplication",
['ui.bootstrap',
    'ui.router',
    'angular-loading-bar',
    'angular-confirm',
    'underscore' //<-- added underscore module here
]);

关于angularjs - 将 Underscore.js 注入(inject) Angular Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38361280/

相关文章:

javascript - 将 2 个对象数组与 Underscore 进行比较以找出差异

javascript - 为什么 "this"被分配给 Controller 内部的变量?

AngularJS 升级(1.5 到 1.6,1.7)使指令范围绑定(bind)未定义

javascript - Angularjs ctrl 单元测试因依赖项失败

angularjs - Angular ng-include 奇怪的行为 - 导致 URL 地址更改

javascript - 使用 Underscore JS _contains 方法检查数组中的键/值对是否存在

javascript - 如何加载整个 AngularJs 应用程序使用的数据?

javascript - 如果 tr 没有子项,则删除它 - ng-repeat - Angular

angularjs - 如何检查我使用的是哪个版本的 Angular?

javascript - Underscore的_.isEqual无法区分2张图片