0

I have my variables bound to this in my controller, and in my route designation I use controllerAs: 'game'. This allows me to include them in my HTML with {{game.var}}. Sometimes, I bind objects that I want to display, but this forces me to write repeatedly {{game.object.a}}, {{game.object.b}}, {{game.object.c}}.

In a previous project using Meteor, I could set the data context with the with keyword.

{{#with object}}
  {{a}}
  {{b}}
{{/with}}

but I don't see a similar feature to this in Angular. The closest I've been able to make work is adding the attribute ng-repeat="object in [game.object]". This works, but it isn't very semantic. This also causes me to get a quick flash of a second element when game.object changes, as the new one loads before the first one is erased.

Is there a better solution to this problem?

1 Answer 1

2

Angular intentionally uses this context scope to avoid confusion between parent and child scopes. If you're not using child scopes, you can skip the controller as syntax entirely and just bind everything to $scope in your model, which turns game.a and game.b to just a and b in your view.

If you are using child scopes, you can still skip controllerAs, but then it becomes confusing what controller a given model in the view belongs to. There's no with or using syntax, so you need to declare the bound scope game.a, childGame.a everywhere you refer to these models, which might be overly verbose but is at least clear.

See this post, as well.

Regarding the flash issue, I would avoid using ng-repeat for semantic purposes. It's primary use case is to display an array of similarly structured data.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm trying to follow the styleguide provided at github.com/johnpapa/angular-styleguide/tree/master where it discourages binding directly to $scope. I am starting to think that every situation where I might prefer this with or using syntax, I should probably be inserting a directive instead, which would mitigate the problem entirely.
Yes, I think this is wise. Directives, when used correctly, have the added benefit of modularizing your view and keeping data encapsulated.
Alright, I will move in that direction. Thank you for your thoughts

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.