且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过从服务功能阵列范围,控制器(AngularJs)?

更新时间:2023-10-27 12:55:04

正如我们所知道的工厂基本上都是用于共享的数据服务。但两者有不同的用途和意义。基本的区别是工厂应该总是返回对象和服务应该(在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