2

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;
4
  • Use the second one. This will have advantages of prevention of digest bugs and IMO it's cleaner (your model is the user, not the scope) Commented Jun 11, 2015 at 8:51
  • The 'big' one makes it easier to have multiple users. But it may just be my preference. This question may be kind of opinion-based... Commented Jun 11, 2015 at 8:51
  • second one is preferable Commented Jun 11, 2015 at 8:51
  • What is the argument for the big one to be the preference? As I am wondering if on changes the whole object needs to be evaluated. Where with the small ones it is only the changed variable. Commented Jun 11, 2015 at 8:52

1 Answer 1

2

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.