簡體   English   中英

如何通過函數更新$ scope變量

[英]How to update $scope variables through a function

我目前正在努力從端點獲取一些數據,然后更新一個名為$scope.response的變量。 我不太確定如何更新此變量並將其呈現在屏幕上。 那么下面的代碼中發生了什么:我從iframe的src屬性獲取查詢字符串,然后將其發布到我的端點,在那里我得到了一個名為data的特定響應。 我想用此對象更新$scope.response ,然后使用{{response}}在視圖上呈現它。

有人可以告訴我我該怎么做嗎?

app.controller('MainCtrl', function($scope) {

  $scope.response;

  API = {};
  API.endpoint = 'https://some/endpoint/';


  function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
      results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
  }

  function doAjax(callback) {
    var q = getParameterByName('QUERY');
    jQuery.ajax({
      url: API.endpoint + "script.php",
      method: "POST",
      data: { q: q },
      dataType: "json",
      success: function (data) {
        callback(data);
        $scope.response = data;
      }
    });
  }

});

Angular並不神奇地知道對象上的屬性何時更改,它必須一直不停地重新檢查所有對象以捕獲此類更改。 當您使用任何Angular服務或事件時,Angular看起來就好像注意到了這些更改,因為這些觸發了摘要周期 在摘要周期結束時,Angular檢查它知道的對象是否有更改,並傳播這些更改(例如,更新視圖等)。

當您使用jQuery時,這就是Angular所不了解的東西。 首先,您不應使用jQuery,而應使用Angular的$http服務來發出任何網絡請求,因為Angular隨后將正確地循環其消化系統。*

*雙關語意

如果您必須使用某些非Angular系統(再一次,您根本不必在這里),那么您需要觸發另一個摘要周期。 最好的方法是使用$timeout服務:

app.controller('MainCtrl', function($scope, $timeout) {

  ...

        success: function (data) {
          callback(data);
          $timeout(() => $scope.response = data);
        }

  ...

});

為什么在Angular中使用jQuery? 如果選擇“ Angular”,則應使用“ $ http”作為“ angular”。 刪除功能doAjax並將其替換為$ http。 您可以在這里https://docs.angularjs.org/api/ng/service/$http閱讀文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM