# all files / Core/Validators/ VariableNameValidator.js

92.86% Statements 26/28
83.33% Branches 5/6
85.71% Functions 6/7
92.86% Lines 26/28

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68

    1
    1

    1

    1
    1
    1
    1

    1

    8

    8

    1
    10
    9
    2

    10
    7

    10

    10
    9
    9
    9

    10
    9
    9
    9

    1
     'use strict';

    // Utilities:
    var _ = require('lodash');
    var Promise = require('bluebird');

    // Module:
    var Core = require('../Core');

    // Dependencies:
    var camelcase = require('change-case').camel;
    var pascalcase = require('change-case').pascal;
    require('../Components/Notifier/NotifierService');
    require('../Services/ValidationService');

    var VariableNameValidator = function (
        $rootScope,
        notifierService,
        validationService
    ) {
        var ModelChangeEvent = 'VariableNameValidator:ModelChange';

        return {
            restrict: 'A',

            require: 'ngModel',

            scope: {
                variableValue: '=ngModel',
                variableNameModel: '='
            },

            link: link
        };

        function link ($scope, element, attrs, ngModelController) {
            var destroy = $rootScope.$on(ModelChangeEvent, function (event, changing) {
                if (ngModelController !== changing) {
                    ngModelController.$validate();
                }
            });

            $scope.$watch('variableValue', function () {
                $rootScope.$broadcast(ModelChangeEvent, ngModelController);
            });

            $scope.$on('$destroy', function () {
                destroy();
            });

            ngModelController.$validators.variableNameUnique = function (value) {
                var allVariableNames = $scope.variableNameModel.getAllVariableNames();
                var result = !_.contains(allVariableNames, value);
                return result;
            };

            ngModelController.$validators.variableNameValid = function (value) {
                var variableName = $scope.$parent.isClass ? pascalcase(value) : camelcase(value);
                Eif (variableName.length === 0) {
                    return false;
                }
                return validationService.validateVariableName(variableName);
            };
        }
    };

    Core.directive('variableName', VariableNameValidator);