user3407039
user3407039

Reputation: 1335

Accessing scope variable in directive

At the moment I have this directive that checks if the username entered by the user already exists in the database -

app.directive('usernameAvailable', function ($timeout, $q, userService, authService) {
    return {
    restrict: 'AE',
    require: 'ngModel',
    link: function (scope, elm, attr, model) {
        model.$asyncValidators.Username = function () {


                var User = {
                    Username: model.$viewValue
                }

                var defer = $q.defer();

                var promiseGet = userService.DoesUsernameExist(User);
                promiseGet.then(function (result) {

                    scope.$emit('updateUsername', model.$viewValue);

                    if (result.data == true) {
                        model.$setValidity('Username', false);
                    } else {
                        model.$setValidity('Username', true);
                    }

                },
                function (errorResult) {
                    console.log('Unable to check if the username exists', errorResult);
                });

                return defer.promise;
            };
        }
    }
});

This works, but my issue is that when you try to edit a user it will say that the username is already taken since it already exists in the database. I want to pass a variable ($scope.InitialUsername) so that i can put a condition in my directive that the username is allowed to equal this when editing a user.

This will also mean passing in a variable for editmode to allow this condition to be checked.

Upvotes: 0

Views: 55

Answers (1)

ckruczek
ckruczek

Reputation: 2410

Take a look at this example Any directive does have a scope variable where you can bind specific informations to

  .directive('myDirective', function() {
  return {
    restrict: 'AE',
    scope: {
      initialUserName: '=name'
    },
  };
})

And in your html you can access this property like this:

<my-directive name="tom"></my-directive>

And on the template side you can query the name like

{{initialUserName.name}}

Upvotes: 1

Related Questions