angularjs – evaluate Expression inside validator directive


I have a custom validation attribute directive that can get expressions, for example:

<input type="text" uiSelectRequired="isParam == true"/>

how do I evaluate this expression in my directive assuming I cannot use isolated scope?


angular.module("app").directive('uiSelectRequired', function () {
        return {
            require: 'ngModel',
            link: function (scope, element, attr, ctrl) {
                ctrl.$validators.uiSelectRequired = function (modelValue, viewValue) {
                    var attrbs = attr;
                    var determineVal;
                    if (angular.isArray(modelValue)) {
                        determineVal = modelValue;
                    } else if (angular.isArray(viewValue)) {
                        determineVal = viewValue;
                    } else {
                        return false;
                    return determineVal.length > 0;


Use attr.uiSelectRequired to get the expression, and use $scope.$eval() to evaluate it.

Note that your usage of the directive is wrong. It should be

<input type="text" ng-model="something" ui-select-required="isParam == true"/>

I’m also usure what you’re trying to do with the angular.isArray() checks. Both the view value and the model value of an input of type text will be a string. Not an array.

Answered By – JB Nizet

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.