0

I am trying to do something like this in Angular javascript (a simplified code):

var modelName = "date";

if (attrs.hasOwnProperty('today')) {
   scope.modelName = new Date();
}

In the above, I actually want scope.modelName to become scope.date automatically. How can I parse the modelName variable to its value?

1
  • 2
    You mean scope[modelName] = new Date() ? Commented Mar 26, 2014 at 20:01

1 Answer 1

8

You can access properties of objects using square brackets.

var modelName = "date";

if (attrs.hasOwnProperty('today')) {
   scope[modelName] = new Date();
}
Sign up to request clarification or add additional context in comments.

11 Comments

yeah... that seems about right. However, in Angular, the new Date() is not updating the ng-model box when I have it as scope[modelName]. However if I type it directly as scope.date then it works.
Could you make a jsFiddle? I'll look over it.
I just tried it in jsFiddle and it works there. It doesnt work in my code only. So I need to review my code and see if I had done a mistake anywhere. Thank you so much for telling me how to access properties of objects. That was exactly what I was looking for. Thanks heaps.. :)
@user2708395 I found out why it wasnt working on my code. It works if I have modelName = "date" but it doesnt work if the modelName = "formData.date". I have a jsfiddle here that shows a sample. Is this not allowed? Here is the jsfiddle link: jsfiddle.net/6fJdk/2
|

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.