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?

JacobPariseau
  • 185
  • 1
  • 13

1 Answers1

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.

Community
  • 1
  • 1
Larry Turtis
  • 1,907
  • 13
  • 26
  • I'm trying to follow the styleguide provided at https://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. – JacobPariseau Nov 05 '16 at 20:07
  • Yes, I think this is wise. Directives, when used correctly, have the added benefit of modularizing your view and keeping data encapsulated. – Larry Turtis Nov 05 '16 at 20:10
  • Alright, I will move in that direction. Thank you for your thoughts – JacobPariseau Nov 05 '16 at 20:11