Reputation: 10703
If you have a controller what is the preferred method for data binding, multiple smaller ones or one big object e.g.:
$scope.username = 'John Doe';
$scope.email = '[email protected]';
$scope.city = 'Amsterdam';
or
var user = {};
user.username = 'John Doe';
user.email = '[email protected]';
user.city = 'Amsterdam';
$scope.user = user;
Upvotes: 2
Views: 71
Reputation: 4350
I would go with second one, from angularjs wiki
Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope. It doesn't work the way most people expect it should work. What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works. New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view and ng-include all create new child scopes, so the problem often shows up when these directives are involved. (See this example for a quick illustration of the problem.)
This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch.
Having a '.' in your models will ensure that prototypal inheritance is in play. So, use
<input type="text" ng-model="someObj.prop1"> rather than
<input type="text" ng-model="prop1">.
If you really want/need to use a primitive, there are two workarounds:
Use $parent.parentScopeProperty in the child scope. This will prevent the child scope from creating its own property. Define a function on the parent scope, and call it from the child, passing the primitive value up to the parent (not always possible)
https://github.com/angular/angular.js/wiki/Understanding-Scopes
Upvotes: 2