使用 AngularJS,我如何绑定 <select>元素到通过服务更新的属性 [英] Using AngularJS, how do I bind a <select> element to an attribute that updates via a service

查看:22
本文介绍了使用 AngularJS,我如何绑定 <select>元素到通过服务更新的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个显示控制器和一个管理控制器.在我的显示控制器中,我有一个下拉选择器,其中包含已选择的项目列表.

我可以获取显示区域下拉列表以更新列表,在管理控制器中添加项目时添加项目,但我不知道如何在下拉列表中选择最新项目.

<select ng-model="item" ng-options="i.name for i in items"></选择>

我制作了一个 jsfiddle 来说明我的情况.不过,最终我的问题是如何将该 ng-model="item" 绑定到由服务更新的数据源.

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

解决方案

嗯,看起来我已经找到了一个相当令人满意的答案.

我通过控制器暴露了存储对象本身

function MyDisplayCtrl($scope, ItemStore) {$scope.items = ItemStore.items;$scope.item = ItemStore.currentItem;//将 itemstore 服务暴露给 dom$scope.store = ItemStore$scope.getItem = function(){返回(ItemStore.currentItem);}}

然后直接寻址currentItem

<select ng-model="store.currentItem" ng-options="i.name for i in items"></选择>

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

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/

解决方案

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/

这篇关于使用 AngularJS,我如何绑定 &lt;select&gt;元素到通过服务更新的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆