Ryan.lay
Ryan.lay

Reputation: 1761

Angularjs $scope.object from nested object

I have a $scope.currentUser object and a nested OwnedCompany object like so:

app.controller 'dashboardsCtrl', ($scope, Api, Auth) ->
  $scope.currentUser = Api.User.get(id: Auth.user())
  $scope.ownedCompany = $scope.currentUser.owned_company

{{currentUser}} returns:

user: { 
  "name": "Ryan",
  "owned_company":{"name":"XYZ"}
}

{{currentUser.owned_company}} returns:

{"name":"XYZ"}

but {{ownedCompany}} returns nil.


How do I get $scope.ownedCompany = $scope.currentUser.owned_company to work?


Solution

As per @mohamedrias' answer,

app.controller 'dashboardsCtrl', ($scope, Api, Auth) ->
  Api.User.get(id: Auth.user()).$promise.then (currentUser) ->
    $scope.currentUser = currentUser
    $scope.ownedCompany = currentUser.owned_company

{{ownedCompany}} returns:

{name:"XYZ"}

Upvotes: 1

Views: 48

Answers (1)

mohamedrias
mohamedrias

Reputation: 18566

  $scope.currentUser = Api.User.get(id: Auth.user())

It's an async call from where you're getting the current user details. So it will resole later.

Either you must use promise ad put

  $scope.ownedCompany = $scope.currentUser.owned_company

Inside the then block.

Else register a watch on that object and perform the assignment.

Upvotes: 2

Related Questions