AngularJS angular binding does not update until some event is fired

so I can't shake this issue due to client restrictions, but in general I have a two-way data binding string that won't update on the html side until some arbitrary event is fired (as soon as any buttons are clicked then it will update, even trivial buttons that just toggle visibility will update it). So if I originally set $ scope.verifiedAddressed1 to "check ..." it will bind the data, but once I change it to "1234 Cherry Lane" it won't update until I click a button on my web page ... The HTML side looks like this:

<p>{{verifiedAddressed1}}</p> // "verifying..."

      

So far the angular code looks like this:

$scope.verifiedAddressed1 = "verifying...";
$scope.verifyAddress = function(isValid){
    if(isValid){
       $.get( "validURL.com", function( data ) {
                $scope.verifiedAddressed1 = data[0].validData;
                console.log($scope.verifiedAddressed1);         //"1234 Cherry Lane"
            });
        }, 400);
        setTimeout(function() {
            console.log($scope.verifiedAddressed1);             //"1234 Cherry Lane"

        }, 700);
    }
}

      

Has anyone seen any weird errors like this before? I've been working with AngularJS for a long time now, and I know that there are many small bugs here and there, especially around button clicks and what not, but I'm sure it has nothing to do with the button event, since any button on the page will activate update two-way binding on checkAddressed1

+3


source to share


1 answer


You should use Angular services to update the scope when you expect it. Instead $.get

, use $http.get

and instead setTimeout

use $timeout

(but only if you really need to work outside the refresh cycle). There was never any reason to call $scope.$apply

yourself - if you use Angular correctly the scope will stay updated.



myApp.controller('MyController', ['$scope', '$http',
  function ($scope, $http) {
    $scope.verifyAddress = function (isValid) {
      if (isValid) {
          $http.get('validURL.com')
            .success(function (data) {
              //...
            })
            .error(function (data, status) {
              //...
            });
      }
    };
}]);

      

+3


source







All Articles