最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using AngularJS, how do I bind a <select> element to an attribute that updates via a service - Stack

programmeradmin10浏览0评论

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.

/

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/

Share Improve this question asked Nov 7, 2012 at 18:58 whtevnwhtevn 5091 gold badge3 silver badges9 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 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/

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论