在Factory中使用值数组

时间:2014-10-17 16:41:10

标签: javascript angularjs

目前我有一个工厂使用包含在$ http.get请求中的json文件。虽然不理想,但这适用于测试。我需要在SharePoint环境中测试相同的解决方案,但不允许使用json文件。最终,这将连接到网络API呼叫。

如何在工厂中指定json值,以便进行测试?

(function() {
var personalViewFactory = function($http) {

    var factory = {};

    factory.getCustomers = function() {
        return $http.get('relationshiptracker.json');
    };



    return factory;
};

personalViewFactory.$inject = ['$http'];

angular.module('customersApp').factory('customersFactory', 
                                       personalViewFactory);

}());

json的例子

[
{
"Segment":"Trading",
"Title":"Narima Ajam ",
"Role":"Oil and Shipping Competency Center Manager ",
"Last Meeting Date":"1/1/2000",
"nextmeetingowner":"",
"CreatedDate":"9/14/2014",
"Modified":"9/14/2014",
"primaryaccountability":"Ajay Buti ",
"otherltEngaged":"Aylin Korkmaz, Carolyn Williams, Karthik Chandrasekar",
"upcomingdate":""
},
{
"Segment":"Upstream",
"Title":"Alison Kenney",
"Role":"IM/IT Manager - The Bridge; (NOLA) - The Bridge",
"Last Meeting Date":"8/5/2014",
"nextmeetingowner":"",
"CreatedDate":"1/2/2000",
"Modified":"2/15/2014",
"primaryaccountability":"Arnold",
"otherltEngaged":"Yero",
"upcomingdate":""
},]

1 个答案:

答案 0 :(得分:0)

只需将JSON放在工厂中的变量上,然后在函数中将其关闭。

http://plnkr.co/edit/gWklBTEZWqxPzQjhV19D?p=preview

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="myCtrl">

    {{myData}}

    <script>
      var app=angular.module("app",[]);

      app.factory("data",function($http){
        var data = [{name:'Bob'},{name:'Amy'}];
        return{
          getData : function(){
            return data;
          }
        }
      });

      app.controller("myCtrl",function($scope,data){

        $scope.myData = data.getData();

      });

      angular.bootstrap(document,["app"]);

    </script>
  </body>

</html>