Javascript 为什么工厂无法访问控制器内部

Javascript 为什么工厂无法访问控制器内部,javascript,angularjs,angularjs-directive,angularjs-scope,angular-ui-router,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,Angular Ui Router,我已经创建了通知工厂并传递了内部控制器,在将工厂分配给范围时传递了内部控制器 alertsManager MyApp.factory('alertsManager', function() { return { alerts: {}, addAlert: function(message, type) { this.alerts[typ

我已经创建了通知工厂并传递了内部控制器,在将工厂分配给范围时传递了内部控制器

alertsManager

 MyApp.factory('alertsManager', function() {
                return {
                    alerts: {},
                    addAlert: function(message, type) {
                        this.alerts[type] = this.alerts[type] || [];
                        this.alerts[type].push(message);
                    },
                    clearAlerts: function() {
                        for(var x in this.alerts) {
                       delete this.alerts[x];
                    }
                    }
                };
            });



  var LoginController = function($scope,$rootScope,alerts,alertsManager)
        {
        $scope.alerts = alertsManager.alerts;
        // getting error.
        **angular.js:11594 TypeError: Cannot read property 'alerts' of undefined**
        }

        LoginController.$inject = ['$scope', '$rootScope','alerts','alertsManager'];


       **why factory not able to access inside controller.*

不需要在控制器中注入“警报”作为依赖项。

对不起..这个问题很愚蠢。。您确定要在Index.html中包含这些文件吗

像这样:

 <script src="app/services/alertsManager.js"></script>

试试下面的方法

代码:

var myApp = angular.module('myApp', []);

myApp.factory('alertsManager', function() {
  return {
    alerts: {'alert':"i'm from factory service"},
    addAlert: function() { //code },
    clearAlerts: function() { //code }
  }
});

myApp.controller('MyCtrl',['$scope','alertsManager', function($scope, alertsManager) {
  $scope.test = alertsManager.alerts.alert;
}]);
注意:将工厂服务注入控制器


工作样本

您正在使用$inject注入4。但是,在函数
LoginController
中有3个。并删除“in”功能。是否有
警报
工厂?是的,所有工厂的情况都是一样的,我无法访问控制器内的工厂功能。制作小提琴或显示更多代码。