How to update $scope variables through a function












0















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

});









share|improve this question


















  • 2





    Don't use jQuery ajax. Use angular $http so you don't have to tell angular to update view. Note settings are a bit different to send form encoded data which is $.ajax default whereas $http default is to send json

    – charlietfl
    Nov 15 '18 at 2:41













  • To use jQuery ajax you need to call $scope.apply() after scope changes. Typically don't need jQuery in angular app though

    – charlietfl
    Nov 15 '18 at 2:45


















0















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

});









share|improve this question


















  • 2





    Don't use jQuery ajax. Use angular $http so you don't have to tell angular to update view. Note settings are a bit different to send form encoded data which is $.ajax default whereas $http default is to send json

    – charlietfl
    Nov 15 '18 at 2:41













  • To use jQuery ajax you need to call $scope.apply() after scope changes. Typically don't need jQuery in angular app though

    – charlietfl
    Nov 15 '18 at 2:45
















0












0








0








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

});









share|improve this question














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

});






javascript angularjs asynchronous






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 15 '18 at 2:34









Jerome PapalieJerome Papalie

295




295








  • 2





    Don't use jQuery ajax. Use angular $http so you don't have to tell angular to update view. Note settings are a bit different to send form encoded data which is $.ajax default whereas $http default is to send json

    – charlietfl
    Nov 15 '18 at 2:41













  • To use jQuery ajax you need to call $scope.apply() after scope changes. Typically don't need jQuery in angular app though

    – charlietfl
    Nov 15 '18 at 2:45
















  • 2





    Don't use jQuery ajax. Use angular $http so you don't have to tell angular to update view. Note settings are a bit different to send form encoded data which is $.ajax default whereas $http default is to send json

    – charlietfl
    Nov 15 '18 at 2:41













  • To use jQuery ajax you need to call $scope.apply() after scope changes. Typically don't need jQuery in angular app though

    – charlietfl
    Nov 15 '18 at 2:45










2




2





Don't use jQuery ajax. Use angular $http so you don't have to tell angular to update view. Note settings are a bit different to send form encoded data which is $.ajax default whereas $http default is to send json

– charlietfl
Nov 15 '18 at 2:41







Don't use jQuery ajax. Use angular $http so you don't have to tell angular to update view. Note settings are a bit different to send form encoded data which is $.ajax default whereas $http default is to send json

– charlietfl
Nov 15 '18 at 2:41















To use jQuery ajax you need to call $scope.apply() after scope changes. Typically don't need jQuery in angular app though

– charlietfl
Nov 15 '18 at 2:45







To use jQuery ajax you need to call $scope.apply() after scope changes. Typically don't need jQuery in angular app though

– charlietfl
Nov 15 '18 at 2:45














2 Answers
2






active

oldest

votes


















2














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

...

});





share|improve this answer































    -1














    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






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311608%2fhow-to-update-scope-variables-through-a-function%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














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

      ...

      });





      share|improve this answer




























        2














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

        ...

        });





        share|improve this answer


























          2












          2








          2







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

          ...

          });





          share|improve this answer













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

          ...

          });






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 15 '18 at 2:51









          decezedeceze

          396k62539695




          396k62539695

























              -1














              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






              share|improve this answer




























                -1














                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






                share|improve this answer


























                  -1












                  -1








                  -1







                  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






                  share|improve this answer













                  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







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 15 '18 at 3:23









                  phuchoangmaiphuchoangmai

                  76111




                  76111






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53311608%2fhow-to-update-scope-variables-through-a-function%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Bressuire

                      Vorschmack

                      Quarantine