Search code examples
javascriptangularjsangularjs-ng-options

How to select option by ID from parent controller in AngularJS


Summary

What's a clean way of updating a select element in a child controller scope so that the selected item's ID matches an ID in a parent scope?

Details

I have two controllers:

  • OrderController
  • CustomerController

OrderController loads an Order and shows it on an order form.

CustomerController is the scope for a subform within the OrderController form. It shows a list of all customers, with the default customer being the one associated with the order. The user can edit the details of the selected customer or add a customer right from the subform.

Possible Solutions

I've thought of two so far, but neither seems very good.

  1. Include a list of all customers in the JSON passed to the Order $resource. That won't work because the user needs a full separate controller to update customers on the subform.
  2. Fire an event when the customers have loaded within CustomerController. OrderController handles that event, updating the select based on its order's customer_id property. That seems better but still hacky.

Solution

  • To communicate between two controllers you would usually broadcast/emit, e.g:

    (Coffeescript)

    CustomerController:

    Api.Customer.get(
      id: $scope.customer_id
    ).$promise.then (data) ->
      $scope.$emit 'event:updateOptionId', id
    

    OrderController:

    $scope.$on 'event:updateOptionId', (event, id) ->
      $scope.customer_id = id
    

    I don't know the structure of your app but this is passing the new customer id to order controller based on an action in the customer controller. If you post some of your code you may get a more thorough answer.