如何通过从服务功能阵列范围,控制器(AngularJs)? [英] How to pass array from service function to scope in controller (AngularJs)?

查看:158
本文介绍了如何通过从服务功能阵列范围,控制器(AngularJs)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的角度服务:

I have an angular service shown below :

    .service('shareDataService', function() {
            var myXi = [];
            var myYi = [];

            var addXi = function(newObj) {
                myXi = newObj;
            }

            var addYi = function(newObj) {
                myYi = newObj;
            }

            var getPlot = function() {
                var a = [];

                for (var i = 0; i < myXi.length; i++) {
                    a.push([myXi[i], myYi[i]]);
                }

                return a;
            }

            return {
                addXi: addXi,
                addYi: addYi,
                getPlot: getPlot
            };
    });

和我有角控制器:

    .controller('plotController', function($scope, shareDataService) {
            $scope.getYo = function() {
                    return shareDataService.getPlot();
            };
            $scope.lineChartData = [
                    $scope.getYo()
            ];
    });

我需要发送从$ scope.getYo至$ scope.lineChartData一个值(它会和数组)。我该怎么办呢?我已经试过这样的,但如果我调用$ scope.lineChartData在HTML中,我什么也没得到。
我需要的数据是

I need to send a value from $scope.getYo to $scope.lineChartData (it will be and array). How can I do that? I've tried like that, but if I call $scope.lineChartData in HTML, I get nothing. The data that I need is

    [
            [
                    [2,0],
                    [3,1],
                    [5,4]
            ]
    ];

更新:

请参阅我的 http://laravel.io/bin/6LVej 完整的解释。谢谢

See my complete explanation in http://laravel.io/bin/6LVej . Thanks

推荐答案

正如我们所知道的工厂基本上都是用于共享的数据服务。但两者有不同的用途和意义。基本的区别是工厂应该总是返回对象和服务应该(在JS构造函数)返回功能。这里是code片段,可能是你的情况有所帮助。

As we know factory and services are basically used for sharing the data. But both have different use and meaning. The basic difference is Factory should always return Object and Service should return Function(constructor function in JS). Here is code snippet that may be helpful in your case.

    var app = angular.module('plunker', []);

app.service('arrayService', function() {
  return function() {
    this.getArray = function() {
      return [1, 2, 3, 4, 5];
    }
  }
})
app.factory('arrayFactory', function() {
  return {
    getArray : function() {
      return [9,8,7,6,5];
    }
  }
})
app.controller('MainCtrl', ['$scope','arrayService','arrayFactory',
  function($scope, arrayService,arrayFactory) {
    var ary = new arrayService();
    $scope.serviceArrayObject = ary.getArray();
     $scope.factoryArrayObject = arrayFactory.getArray()

  }
]);

这里是基本的区别plunker
 我们如何使用服务和工厂

Here is the plunker for basic difference How we use service and factory

这篇关于如何通过从服务功能阵列范围,控制器(AngularJs)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆