Jerome Papalie
Jerome Papalie

Reputation: 49

How to update $scope variables through a function

I'm currently working on grabbing some data from an endpoint and then updating a variable called $scope.response. I'm not quite sure how to update this variable and render it on screen. So what happens in the code below: I get the query string from an iframe's src attribute, and then post it to my endpoint, where I get a particular response called data. I'd like to update $scope.response with this object, and then render it on the view using {{response}}.

Could someone show me how I could do this?

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;
      }
    });
  }

});

Upvotes: 0

Views: 404

Answers (2)

phuchoangmai
phuchoangmai

Reputation: 305

Why do you use jQuery in Angular?. If you choose Angular, you should be you $http in angular. Remove function doAjax and replace it to $http. You can read doc in here https://docs.angularjs.org/api/ng/service/$http

Upvotes: -1

deceze
deceze

Reputation: 522636

Angular doesn't magically know when a property on an object changes, it would have to keep re-checking all objects all the time to catch such changes. Angular just makes it look like it notices such changes whenever you use any Angular services or events, since those trigger a digest cycle. At the end of a digest cycle, Angular checks objects it knows about for changes and propagates those changes (e.g. updates views etc.).

When you use jQuery, that's "outside" of what Angular knows about. Primarily you should not use jQuery, but Angular's $http service to make any network requests, since Angular will then properly cycle its digestive system.*

* Pun totally intended

If you have to use some non-Angular system (and again, you really don't have to here, at all), then you need to trigger another digest cycle. The best way to do that is with the $timeout service:

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

  ...

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

  ...

});

Upvotes: 2

Related Questions