0

I have the following Javascript variable:

scope.model = {
  errors: {
    email: ["error1", "error2"],
    name: ["error"]
  }
}

And I have a function as follows:

function (scope, element, attributes) {            
  if (scope.model.errors) {
    if (scope.model.errors[attributes.validator]) 
      // Do something
}

The problem is that the errors are not always on the same scope variable.

I can have something like:

scope.view = {
  newErrors: {
    email: ["error1", "error2"],
    name: ["error"]
  }

Inside the function I know how to get the variable where they are:

function (scope, element, attributes) {            

  var errors = attributes["validatorErrors"];

  // Note: errors is this case "view.newErrors"
  // So the following code would become: 

  if (scope.view.newErrors) {
    if (scope.view.newErrors[attributes.validator]) 
      // Do something
}

UPDATE

I have tried [] before but now I understand why it was not working:

function (scope, element, attributes) {            

  var errors = attributes["validatorErrors"];

  if (scope[errors]) {
    if (scope.[errors][attributes.validator]) 
      // Do something
}

If errors = 'errors' it will work ...

If errors = 'model.errors' it won't. In this case I would need:

scope['model']['errors'] ...

How can I solve this?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • 3
    I'm not sure what you're asking here. – Stefan Kendall May 08 '15 at 11:13
  • 1
    do you mean you want to dynamically get an object's property? if so, use the [] notation to access it, ie `scope[errors]`, [property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) – Patrick Evans May 08 '15 at 11:16
  • It won't work when errors = "model.errors". I will work if errors = "errors". See my last update. How to solve this? – Miguel Moura May 08 '15 at 11:39

2 Answers2

0

Use the array notation:

if (scope[errors]) {
  if (scope[errors][attributes.validator]) {
    // do something
MueR
  • 977
  • 7
  • 13
  • It won't work when errors = "model.errors". I will work if errors = "errors". See my last update. How to solve this? – Miguel Moura May 08 '15 at 11:39
  • If you want that level of options, you will need to use a loop to parse that string. Split by the dot, loop over all elements. – MueR May 08 '15 at 21:26
0

You actually already know the answer because youre using it in your example.

scope[newErrors][attributes.validators]

Just be careful here because it will break when scope[newErrors] is undefined. So some error handling might be needed

PhilVarg
  • 4,762
  • 2
  • 19
  • 37
  • I tried that before and now I understand why it was not working. If errors is something like "errors" it will work but if it is something like "model.errors" it won't work. Please, see my last uptade. – Miguel Moura May 08 '15 at 11:36