chris13524 chris13524 - 2 years ago 90
AngularJS Question

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

. If I print out the
, 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:

Answer Source

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.


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download