Chris Smith
Chris Smith

Reputation: 3012

Scope contains value, but when accessing it, it's undefined

I'm writing an AngularJS directive, and when I try to access a scope variable, it's undefined. If I print out the scope, I can clearly see that the variable has a value.

Check your JavaScript console, that's where I'm print this stuff to.

Here's a Plunker thing: http://plnkr.co/edit/1cSVZJgtlUazOqTuCNOK

Upvotes: 2

Views: 51

Answers (1)

ryeballar
ryeballar

Reputation: 30118

This is because the <form> directive which provides the values for the form value has not been compiled yet when the usernameAvailable has been compiled, since it is clearly a child scope of form. The reason why you would see the usernameAvaiable value when using console.log() is because it prints the reference of the $scope object (this means the latest value that it had). If you really want to access such value, a workaround would be to use $timeout() to access the value.

DEMO

app.directive('usernameAvailable', ['$http', '$q', '$timeout', function($http, $q, $timeout) {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      usernameAvailable: '='
    },
    link: function(scope, elem, attr, controller) {
      $timeout(function() {
        scope.usernameAvailable.$asyncValidators.usernameAvailable = function(username) {
          if (typeof(getCurrentUsername) != 'undefined' && username == getCurrentUsername()) {
            return $q.resolve();
          } else {
            return $http.get('/user/usernameAvailable?username=' + username).success(function(result) {
              if (result) {
                return $q.resolve();
              } else {
                return $q.reject();
              }
            });
          }
        };  
      });

    }
  }
}]);

Upvotes: 2

Related Questions