angular.js $ http.error没有状态返回json

时间:2014-07-07 14:20:56

标签: json angularjs http status

我是Angular.js的新手,我正在关注角网站的教程。

我正在尝试使用$ http服务从json文件获取数据,但没有任何反应! 即使错误的状态也不起作用......

这是我的代码:

 <li>{{status}}</li>

 <ul class="messages">
      <li ng-repeat="message in messages">
            {{message.title}}
            <p>{{message.title2}} {{message.icon}}</p>    
      </li>
 </ul>

和js部分:

var monitorControllers = angular.module('monitorControllers', []);

monitorControllers.controller('MonitorCtrl', ['$scope', '$http',
    function($scope,$http) {
   $http.get('data/messages.json').success(function(data, status) {
       $scope.status = status;
       $scope.messages = data;
   }).error(function(data, status) {
           $scope.messages = data || "Request failed";
           $scope.status = status;
       });    

}]);

解决方案:

谢谢sylwester,我发现了问题,但这真的很奇怪。所以我刚刚在我的js文件中添加了这个: (在开头和结尾......)

(function () {
    var monitorControllers = angular.module('monitorControllers', []);

    monitorControllers.controller('MonitorCtrl', ['$scope', '$http',
        function ($scope, $http) {

            $http.get('data/messages.json').success(function(data, status) {
             $scope.status = status;
             $scope.messages = data;
             }).error(function(data, status) {
             $scope.messages = data || "Request failed";
             $scope.status = status;
             });


        }]);
})();

1 个答案:

答案 0 :(得分:5)

更有可能你错过了什么,请看那里:http://jsbin.com/canuma/1/edit?html,js,output

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-app="monitorControllers">
  <div ng-controller="MonitorCtrl">
   <li>{{status}} {{messages}}</li>

 <ul class="messages">
      <li ng-repeat="message in messages">
            {{message.title}}
            <p>{{message.title2}} {{message.icon}}</p>    
      </li>
 </ul>
      </div>
</body>
</html>

JS:

var monitorControllers = angular.module('monitorControllers', []);

monitorControllers.controller('MonitorCtrl', function($scope, $http){

  $http.get('data/messages.json').success(function(data, status) {
       $scope.status = status;
       $scope.messages = data;
   }).error(function(data, status) {
           $scope.messages = data || "Request failed";
           $scope.status = status;
       });  


});