user2872493
user2872493

Reputation:

AngularJS databinding not updating until arbitrary event is fired

so I can't really make a fiddle out of this problem 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(Once any buttons get clicked then it will update, even trivial buttons that just toggle visibility will update it). So if I initially set the $scope.verifiedAddressed1 to equal "verifying..." it will data bind, but once I change it to "1234 Cherry Lane", it will not update until I click some button on my webpage. The html side of things looks like this

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

While the angular code looks like the following:

$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 bugs like this before? I've been working with AngularJS for a little while now and I know there are still a lot of little bugs here and there especially around button clicks and what not, but I am fairly sure this has nothing to do with a button event since any button on the page will activate the two way binding update on verifiedAddressed1

Upvotes: 3

Views: 1073

Answers (1)

Carson Myers
Carson Myers

Reputation: 38564

You should use Angular's services to keep the scope updating when you expect it to. Instead of $.get, use $http.get, and instead of setTimeout, use $timeout (but only for when you really need to work outside of the update loop). There's never really a reason to call $scope.$apply yourself - if you use angular properly, 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) {
              //...
            });
      }
    };
}]);

Upvotes: 3

Related Questions