【问题标题】:accessing returned value from a second function from controller从控制器访问第二个函数的返回值
【发布时间】:2017-06-12 14:49:01
【问题描述】:

我有一个控制器,可以加载带有选项卡式面板的视图。根据用户单击的项目,在调用函数select 时将数据作为参数传递。

第一个选项卡工作正常,显示来自返回对象的数据。

第二个选项卡包含一个图表。为了确保向图表提供正确的数据集,我需要从第一个面板中返回的对象中获取id。在我创建的服务loadPatentItemService 中,当我记录返回的项目时,它会显示正确的信息,但是当我从我的控制器lineCtrl 调用此服务时,它会记录undefined

厂内登录loadPatentItemService服务getPatent

console.log(item)

记录lineCtrl中调用服务的返回值

undefined

可能是当我调用它时,它第二次调用它并且数据被重置,因为没有参数被传递给函数。

基本上,为什么我不能从服务loadPatentItemService 访问我的控制器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);
    }
}])

【问题讨论】:

  • 你的getParent 函数基本上什么都不做。它接受一个参数并返回它,仅此而已。不带参数调用它会返回undefined。您可能希望将数据存储为 this 的属性并返回 that

标签: javascript angularjs


【解决方案1】:

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;
})

【讨论】:

  • 那是我愚蠢的。感谢您的时间和榜样!你知道我的问题的问题吗? IE。为什么它被否决了?
  • 我不知道为什么你的问题被否决了。这是一个格式正确的问题,有足够的信息进行调试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
相关资源
最近更新 更多