23

I have a display controller and a management controller. Inside my display controller, I have a dropdown selector with the list of items that have been selected.

I can get the display area dropdown to update the list, adding items as they are added in the management controller, but I cannot figure out how to select the newest item in the dropdown.

<div ng-controller="MyDisplayCtrl">
  <select ng-model="item" ng-options="i.name for i in items">
  </select>
</div>

I have made a jsfiddle to illustrate my situation. Ultimately, though, my question is how to bind that ng-model="item" to a data source updated by a service.

http://jsfiddle.net/whtevn/mUhPW/2/

0

2 Answers 2

15

Well, it looks like I've found a pretty satisfactory answer to this.

I exposed the storage object itself through the controller

function MyDisplayCtrl($scope, ItemStore) {
    $scope.items = ItemStore.items;
    $scope.item  = ItemStore.currentItem;

    // expose the itemstore service to the dom
    $scope.store = ItemStore

    $scope.getItem = function(){
        return(ItemStore.currentItem);
    }
}

and then address the currentItem directly

<div ng-controller="MyDisplayCtrl">
    <select ng-model="store.currentItem" ng-options="i.name for i in items">
    </select>
</div>

http://jsfiddle.net/whtevn/Cp2RJ/3/

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

3 Comments

this works well, and I have moved to it as my default pattern, but if someone has a reason that I should not be calling exposed services in my views, I would like to hear it
One reason I can think of is caching. If the functionality of your service changes, then you will have to modify your view, which may be aggressively cached, instead of the innards of your controller. In my experience it is easier to uncache external JavaScript files and this would be a purer separation of concerns. Let your controller populate scope and your view access that scope.
Through a video I watched on a training site, using exposed services in views is good practice. However, how the services are written and constructed were recommended using a revealing module pattern rather than giving access to variables return the functions and properties that should be publicly acceptable: addyosmani.com/resources/essentialjsdesignpatterns/book/…. In addition, the services were created using .factory method rather than .service.
4

Try using ng-options:

<div ng-controller="MyDisplayCtrl">
    <select ng-options="i.name for i in items"></select>
</div>

See: http://docs.angularjs.org/api/ng.directive:select

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.