我有一个 Controller 可以加载带有选项卡式面板的 View 。根据用户单击的项目,调用函数 select
时将数据作为参数传递。
第一个选项卡工作正常,显示来自返回对象的数据。
第二个选项卡包含一个图表。为确保向图形提供正确的数据集,我需要从第一个面板中返回的对象中获取 id
。在我创建的服务 loadPatentItemService
中,当我记录返回的项目时,它会显示正确的信息,但当我从我的 Controller lineCtrl
调用此服务时,它会记录 未定义
。
登录工厂 loadPatentItemService
服务 getPatent
console.log(item)
在 lineCtrl
中记录调用服务的返回值
未定义
可能是当我调用它时,它正在第二次调用它并且数据被重置,因为没有参数被传递给函数。
基本上,为什么我不能通过服务 loadPatentItemService
从我的 Controller lineCtrl
访问数据?
app.factory('loadPatentItemService', function() {
return {
select: function(item) {
var patentItem = [];
patentItem.push(item);
this.getPatent(patentItem);
return patentItem;
},
getPatent: function(item) {
// var hello = 'hello';
// console.log(item);
return item;
}
}
})
app.controller("lineCtrl", ['$scope', 'loadPatentItemService', function ($scope, loadPatentItemService) {
console.log(loadPatentItemService.getPatent());
}])
app.controller('patentListCtrl', ['$scope', 'loadPatentItemService', function($scope, loadPatentItemService) {
//FUNCTION INVOKED BY USER CLICKING ON ITEM IN TABLE
$scope.select = function(item) {
$scope.patentItem = loadPatentItemService.select(item);
}
}])
最佳答案
在select
函数中,您需要将选择的项目存储在服务中,以便您可以在getPatent
函数中将其发回。
尝试将您的 loadPatentItemService
更改为此
app.factory('loadPatentItemService', function() {
var service = {
selectedItem: null;
select: function(item) {
service.selectedItem = item;
return [selectedItem]; // Returning an array since your original post was returning an array
},
getPatent: function() {
return service.selectedItem ;
}
}
return service;
})
关于javascript - 从 Controller 的第二个函数访问返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44502377/