【发布时间】: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