服务器内没有响应的服务

时间:2014-05-29 08:59:18

标签: angularjs angularjs-service

我对angularjs很新。我很难将本地json数据导入控制器

这是.js文件:

'use strict';

angular.module('angularPlaygroundApp').factory('campaignService', function($http) {
  return $http.get('data/campaign.json');
})
.controller('CampaignCtrl', function ($scope, campaignService) {
    $scope.name  = '';
    campaignService.success(function(data){
      console.log('check');
      $scope.name = data.compaigns;
      console.log(data);
    });
  });

即使控制器内的console.log没有给出响应。

如果我犯了一些错误,请告诉我。

您可以在此处查看我的目录结构 You can watch my directory structure here

1 个答案:

答案 0 :(得分:1)

您需要在工厂声明中创建一个对象并返回该对象。

angular.module('angularPlaygroundApp').factory('campaignService', function($http) {
  var fact = {};
  fact.getData = function() {
    return $http.get('data/campaign.json');
  };

  return fact;
})

在您的控制器中,您可以使用

campaignService.getData()....

这里是整个代码(模块decrlaration中也有错误):

campaign.json(从维基百科上复制了一些数组代码):

    {
    "campaigns": 
        [
        { "type": "home", "number": "212 555-1234" },
        { "type": "office",  "number": "646 555-4567" }
    ]
}

的index.html:

<!doctype html>
<html lang="en" ng-app="angularPlaygroundApp">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body >
    <script src= "angular.js"></script>

    <script src= "script.js"></script>

    <div ng-controller='CampaignCtrl'>
        {{name}}
    </div>

</body>
</html>

的script.js:

angular.module('angularPlaygroundApp', [])

.factory('campaignService', function($http) {
  var fact = {};
  fact.getData = function() {
    return $http.get('data/campaign.json');
  };

  return fact;
})

.controller('CampaignCtrl', function ($scope, campaignService) {
    $scope.name  = [];

    campaignService.getData()
    .success(function(data){
      $scope.name = data.campaigns;
      console.log(data);
    })
    .error(function(data) {
      console.log('error');
    });

  });