将对象通过服务单击传递到另一个控制器

时间:2017-03-12 23:44:18

标签: angularjs angular-services

我要做的是使用ng-click将ng-repeat中的当前对象传递给控制器​​函数。

<div ng-controller="ScheduleCtrl as vm" >               
<div ng-repeat="item in vm.items">   
<div ng-click="vm.select(item)">

第一个控制器根据服务进行注册,并使用上述方法定义如下。

var app = angular.module('ascensionApp');
app.controller("ScheduleCtrl", ["$scope", 'ScheduleService', 

function(ScheduleService) {
    var vm = this; 
vm.select = function(scheduleItem){
            ScheduleService.save(scheduleItem);
        };
}]);

服务已注册到模块,并使用save方法定义如下,以将传入对象接受到作用域中,以及返回对象的方法。

app.service('ScheduleService', function() {

var scheduleItem = {};


this.save = function(scheduleItem){
    scheduleItem.pop();
    scheduleItem.push(scheduleItem);
};

this.show = function(){
    return scheduleItem;
};
});

单独元素的控制器尝试访问数据。

app.controller("DashboardCtrl", ["$scope", 'ScheduleService', function($scope, ScheduleService) {
    $scope.data = ScheduleService.show();
}]);

然后它将显示在视图上,如下所示:

<div id="dashboard" ng-controller="DashboardCtrl">
<h1 class="mdl-card__title-text" id="headline">
                        It's time for {{data.name}} 
</h1>

我是Angular的新手,但一直在研究使用自定义服务。现在我收到的错误是:

ScheduleService.save不是函数

我尝试了许多创建服务方法的变体,但要么没有取得任何成功,要么就是上面的错误。有人可以解释一下我做错了什么吗?

非常感谢你!

1 个答案:

答案 0 :(得分:0)

ScheduleService未定义控制器中错误的b / c。

当您声明一个控制器并指定要注入的事物的名称时,控制器函数必须以相同的顺序将那些相同的依赖项列为函数参数,如下所示:

app.controller("ScheduleCtrl", ["$scope", 'ScheduleService', 

function($scope, ScheduleService) {