javascript - 从 Controller 的第二个函数访问返回值

标签 javascript angularjs

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

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

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

登录工厂 loadPatentItemService 服务 getPatent

console.log(item)

enter image description here

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/

相关文章:

javascript - 如何知道 AngularJS 中一长串的异步调用何时完成?

php - 如何使用 PHP 或 javascript 显示与用户相同时区的日期时间?

javascript - 在jsTree中,我们如何在替换树后初始选择节点?

javascript - 在 AngularJS 中观察对象

javascript - 使用 ngStorage(angularjs) 作为语言选项

javascript - 元素在 Safari 的某些实例中意外隐藏,但始终出现在 Firefox、Chrome 中

javascript - ng-repeat 切换幻灯片,但其他应该接近

javascript - jQuery.post 返回 400 错误请求错误 [rails]

php - 制作 'mobile/cell' 版本的 PHP/Javascript 网站?

javascript - 从 javascript 调用 React 组件函数