0

How to use a string as a variable within the scope. Heres my code:

HTML (one of many divs like this where type1 can be type2, type3, and so on):

<div style="color:red;font-size:11px;">{{ error.type1 }}</div>

controller:

$scope.validate = function(string, value){
        // lets say string = type1
        if (value != 'answer'){
            $scope.error.string = 'Incorrect, try again';
        }
    }

How can I run $scope.error.type1 = 'Incorrect'? I have many different errors on a form above each input field and the validate function is called when a value is entered. My goal is to avoid writing a TON of conditionals based on what the string is equal too. How can I use this dynamically?

1
  • Do you mean $scope.error.type1 instead of $scope.error.string in your example? Also if you could give more examples of what your different errors look like, that would be helpful. Commented May 16, 2021 at 18:46

1 Answer 1

0

I might be getting this all wrong, but how about a reusable directive?

<input type='email' ng-model='user.email' />
<error-feedback field='email' errors='errors'></error-feedback>

<input type='text' ng-model='user.name' />
<error-feedback field='name' errors='errors'></error-feedback>

the controller

$scope.errors={}
if (!isValid(user.email)) {
   setError('email','Your email is not valid');
}

if (alreadyExists(user.email)) {
   setError('email','This email already exists');
}

const setError = function(type, error) {
   if ($scope.errors[type]) $scope.errors[type].push(error);
  else $scope.errors[type] = [error];
}

the directive

app.directive('errorFeedback', ['$compile', '$templateCache',
         function($compile, $templateCache) {
             return {
                 template: "<div ng-repeat='error in myerrors' class='error'>{{error}}</div>",
                 scope: {
                     field: "=",
                     errors: "="
                 },
                 controller: ["$scope", "$timeout",
                     function($scope, $timeout) {
                            // assuming errors might be an array
                            $scope.myerrors = $scope.errors[$scope.field]
                     }
                 ],
                 link: function(scope, element, attr) {}
             }
         }
     ])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.