在角度控制器

时间:2016-06-05 19:56:29

标签: javascript angularjs json http

我有一个包含json对象的角度控制器

app.controller("buildControl", function($scope){

$scope.buildData = [
{
    'title':'Workspace',
    'options': [{
        'title': 'Studio'
    },{
        'title': 'Garage'
    },{
        'title': 'Blank'
    }]
},{
    'title':'Frame',
    'options': [{
        'title': 'Studio'
    },{
        'title': 'Garage'
    },{
        'title': 'Blank'
    }]
}]
});

我使用这些数据使用ng-repeat迭代对象的数组(另外我的控制器中还有其他使用数据的函数)。

一切运行正常,直到我将json移到它自己的文件中并使用$ http来包含它。

app.controller("buildControl",function($http, $scope){

$http.get("json/buildData.js")
  .success(function(response){
    $scope.buildData = response.data;
  }).error(function(error){
    console.log(error);
  });
});

我在控制台中遇到的唯一错误来自我的所有其他功能,没有他们需要运行的数据,还有一个未定义的'从我的控制台日志。所以我知道它会进入' .error'。

我想也许我有错误的文件路径,尝试更改前缀为' ../'从我的控制器上升一个目录。没运气。如果我把json放在同一个文件夹中然后写;

.get("buildData.js")

我将此作为错误

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /buildData.js was not found on this server.</p>
</body></html>

然后我整理了文件路径,它又回到了未定义的状态。所以我不认为这是问题所在。

(我使用MAMP执行此操作并且没有与尝试在本地获取文件相关的HTTP错误。)

任何帮助?

1 个答案:

答案 0 :(得分:2)

不确定您是否需要在此处使用$ http,为什么不在服务中包含您的数据,例如:

  angular
    .module('MyApp')
    .service('buildData', buildData);

  function buildData() {
    return [{
      'title':'Workspace',
      'options': [{
         'title': 'Studio'
      },{
        'title': 'Garage'
      },{
        'title': 'Blank'
      }]
    ...
    }]
  };

您的控制器看起来像这样:

.controller('buildControl', buildControl);

  buildControl.$inject = ['$scope', 'buildData'];
  function buildControl($scope, buildData) {
    $scope.buildData = buildData;
    ...
  }