AngularJS でローカルの json ファイルを読み込む

AngularJS で json ファイルを読み込みたい場合は angular-resource を使用します。


[index.html]

<html ng-app="phonecatApp">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular-resource.min.js"></script>
    <script src="./script.js"></script>
  </head>
<body ng-controller="PhoneListCtrl">
  <input type="text" ng-model="query.snippet" placeholder="検索">
  <ul class="phones">
    <li ng-repeat="phone in phones | filter:query">
      {{phone.name}}
      <p>{{phone.snippet}}</p>
    </li>
  </ul>
</body>
</html>

[script.js]

var phonecatApp = angular.module('phonecatApp', ["ngResource"]);


phonecatApp.controller('PhoneListCtrl', ["$scope", "$resource", function ($scope, $resource) {
    var contents = $resource("./data.json");
    // List(一番外側 [])を取得する場合は query()
    // Object(一番外側が {}) get() を使用する
    $scope.phones = contents.query();
}]);

[data.json]

[
    {"name": "Nexus S",
     "snippet": "Fast just got faster with Nexus S."},
    {"name": "Motorola XOOM™ with Wi-Fi",
     "snippet": "The Next, Next Generation tablet."},
    {"name": "MOTOROLA XOOM™",
     "snippet": "The Next, Next Generation tablet."}
]


Chrome だとローカルのファイルを読み込むことが出来にないので注意してください。
Firefox では問題なく読み込むことが出来ます。
Chrome でも読み込みたい場合はここら辺を参照してください。