从 jquery 到 angularjs

From jquery to angularjs

我正在使用以下格式从本地主机获取 JSON 对象。 JSON 非常复杂且冗长,因此使用 jquery 填充 HTML 变得越来越复杂。

function processmsg(msg) {
        var jobj = JSON.parse(msg);
        if (typeof jobj === 'object')
        {
            // Parse the JSON
            }
            document.getElementById("messages").innerHTML = globalTag;

        }
    }

    function waitForMsg() {
        $.ajax({
            type: "GET",
            url: "1.json",

            cache: false,
            timeout: 50000,

            success: function (data) {
                processmsg(data);
                if (!data) {
                    setTimeout(
                        waitForMsg,
                        1000
                    );
                };
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {

                setTimeout(waitForMsg, 15000);
                processmsg("error");
            }

        });
    };

    $(document).ready(function () {
        waitForMsg();
        processmsg("loading");
    });

我想使用 {{jobj.entries}} 这样的格式。像这样的东西。这可以在 angularJS 上完成。你们能建议我如何在 angular 中做同样的事情吗?

我想每 1 分钟查询一次 JSON,当找到数据时我想取消间隔。我不知道如何在 angularjs 中做到这一点。

==================更新================ 我得到了下面的代码片段。它工作正常,但是一旦获得 json 对象,我如何停止 url 查询..

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

    app.controller('jsonController', function($scope, $http) {

      $scope.getData = function(){
        var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
        $http.get(url)
          .success(function(data, status, headers, config) {
            console.log(data);
          });
      };
      if (!$scope.data){
        setInterval($scope.getData, 2000);
      }

这里的问题是 json 对象仅在 3 秒后可用。

假设您有以下 JSON 数据存储在名为 data 的范围变量中:

$scope.data = {
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
}

然后你用下面的方式写你的HTML:

<div>
    Boolean: {{data.boolean}}
</div>
<div>
    Number: {{data.number * 2}}
</div>
<div>
    Array:
    <p ng-repeat="(key, value) in data.object"> {{key}} : {{value}}</p>
</div>
Another way to bind <div ng-bind="data.string"></div>

在这里您可以停止通话。您可以为此使用增强的 angular 服务 $interval

$scope.getData = function(){
    var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
    $http.get(url)
    .success(function(data, status, headers, config) {
        console.log(data);
        $interval.cancel($scope.intervalObject);    // cancel the interval when data is loaded
     });
};

if (!$scope.data){
    $scope.intervalObject = $interval($scope.getData, 2000);
}
var app = angular.module('urlanalyzer', []);

app.controller('jsonController', ['$scope','$http','$timeout',function($scope, $http, $timeout) {

  $scope.getData = function(){
    var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
    $http.get(url)
      .success(function(data, status, headers, config) {
          if(!data)
             $timeout(function(){
                $scope.getData()
             }, 2000)
          else{
             $scope.myData = data.data? data.data:data;
             $scope.showError = false;
          }


      })
       .error(function(msg) {
          $timeout(function(){
              $scope.getData()
          }, 2000)
          $scope.processMessage(msg)
      });
  };
  $scope.processMessage = function(msg){
      if(angular.isString(msg))
       $scope.errorMessage = msg;
     else if(angular.isObject(msg)){
        $scope.errorMessage = msg.message // the property you want;
     }
     $scope.showError = true;
  }
  $scope.getData();
}])

HTML:

 <div ng-controller="jsonController">
      <div ng-show="showError">
        {{errorMessage}}
      </div>
      <div id="myDatacontainer">
           //you can bind any propery of your data by using angular direvtives
           //look at ng-bing, ng-if etc. directives
          {{myData.name}} ...
      </div>
 </div>

希望对您有所帮助。

  if (!$scope.data){
    setInterval($scope.getData, 2000);
  }

由于未设置 $scope.data,它将继续调用请求(因为您没有在任何地方设置 $scope.data)。

编辑:此外,使用 angularjs $interval,因为它是 angular 使用 setInterval 的方式,它会跟踪 $digest 周期