Alan A
Alan A

Reputation: 2551

Initialization of Angular objects

I have an Angular 1.x app and I want to initialize some $scope variables:

$scope.listing = {};
$scope.listing.title = 'This is a test';
$scope.listing.description = 'blah';

I also want to initialize an empty object, as follows:

$scope.listing.payment_types._ids = {};

This fails:

angular.js:14328 TypeError: Cannot read property '_ids' of undefined

Seems I must do this:

$scope.listing.payment_types = {};
$scope.listing.payment_types._ids = {};

It seems long-winded, is there a more concise way?

Upvotes: 0

Views: 44

Answers (1)

georgeawg
georgeawg

Reputation: 48968

Nest the literals:

$scope.listing.payment_types = { _ids: {} };

The advantage of the object literal notation is, that you are able to quickly create objects with properties inside the curly braces.

For more information, see

Upvotes: 3

Related Questions