我已经创建了通知工厂并传入内部控制器,内部控制器将工厂分配给范围获取错误。
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.*
答案 0 :(得分:1)
尝试以下内容。
<强>码强>
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;
}]);
注意:将 工厂服务 注入控制器
工作样本 here 。
答案 1 :(得分:0)
无需注入&#39;提醒&#39;作为控制器中的依赖。
答案 2 :(得分:0)
抱歉..非常愚蠢的问题..你确定在Index.html中包含这些文件吗?
像这样: <script src="app/services/alertsManager.js"></script>