JacobPariseau JacobPariseau - 3 months ago 30
AngularJS Question

Set context scope in Angular

I have my variables bound to

in my controller, and in my route designation I use
controllerAs: 'game'
. This allows me to include them in my HTML with
. Sometimes, I bind objects that I want to display, but this forces me to write repeatedly

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

{{#with object}}

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
changes, as the new one loads before the first one is erased.

Is there a better solution to this problem?


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.