【问题标题】:Passing an Object On-Click Through a Service to Another Controller通过服务将对象单击传递给另一个控制器
【发布时间】:2017-03-12 23:44:18
【问题描述】:

我想要做的是使用 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 不是函数

我尝试了许多创建服务方法的变体,但要么没有成功,要么出现上述错误。有人可以解释我做错了什么吗?

非常感谢!

【问题讨论】:

    标签: angularjs angular-services


    【解决方案1】:

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

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

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

    【讨论】:

    • 嘿,谢谢你提醒我!稍作调整后,这些方法开始起作用。我必须在第一个控制器的方法中使用 $rootscope 并向我的第二个控制器广播一个事件,以便让它在第二个控制器区域上更新。
    猜你喜欢
    • 1970-01-01
    • 2016-04-08
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多