我想要做的是使用 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不是函数
我尝试了许多创建 Service 方法的变体,但要么没有成功,要么出现上述错误。有人可以解释一下我做错了什么吗?
非常感谢!
该ScheduleService
是你的控制器错误未定义B / C。
当您声明一个控制器并指定要注入的事物的名称时,控制器函数必须具有以相同顺序列为函数参数的相同依赖项,如下所示:
app.controller("ScheduleCtrl", ["$scope", 'ScheduleService',
function($scope, ScheduleService) {
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句