【问题标题】:Multiple select in angularjs formangularjs形式的多项选择
【发布时间】:2015-05-09 15:17:27
【问题描述】:

我有一个简单的表单,用于通过 REST API 编辑现有对象(事件)。如果 id 作为参数传递,我的控制器会调用服务来预填表单。

这是html代码:

<div class="jumbotron">
    <div ng-controller="PersonListCtrl">
      <form novalidate class="simple-form" ng-controller="EventController">
        Title*: <input type="text" ng-model="event.title" /><br />
        Subtitle: <input type="text" ng-model="event.subtitle" /><br />
        Speakers:
        <select
            multiple ng-model="event.speakers"
            ng-multiple="true"
            ng-options="person.id as person.name for person in persons">
        </select><br />
        <input type="submit" ng-if="event.id" ng-click="update(event)" value="Save" />
        <input type="submit" ng-if="!event.id" ng-click="create(event)" value="Create" />
      </form>

      <pre>event: {{event | json}}</pre>
      <pre>speakers: {{event.speakers | json}}</pre>
    </div>

这里是控制器:

jugtaasApp.controller('EventController', function($scope, $http, $routeParams) {

    $scope.event = {};

    $scope.update = function(event) {
        // TODO: update
    };

    $scope.create = function(event) {
        // TODO: create
    };

    if(!$routeParams.id) {
        return;
    }

    $http.get('services/events/' + $routeParams.id)
    .success(function(data) {
        $scope.event = angular.copy(data);
        $scope.event.speakers = [$scope.persons[0]];    
    });
});

PersonListCtrl 调用另一个服务来检索可用发言人的列表。

使用此代码可以正确调用服务/事件,并且正确填写字段(标题和副标题),但多选(发言人)除外。

多选包含所有可用的人,但如果活动有一些演讲者,他们不会被选为选项。

我该怎么办?

【问题讨论】:

  • $scope.persons 未在显示的内容中定义
  • $scoper.persons 由 PersonListCtrl 设置,它调用服务来列出可用人员。多重选择被正确呈现,所有的人,但没有预先选择。
  • 需要使用服务来跨控制器共享数据或访问$parent,因为它们是嵌套的
  • 同样使用:$scope.event.speakers = [$scope.$parent.persons[0]]; 结果是一样的
  • 我提到了$parent,但是使用服务是最好的方法

标签: angularjs forms select


【解决方案1】:

问题在于 select 的使用,因为使用以下指令(并且没有更改)它可以工作:

<select multiple ng-multiple="true"
    ng-model="event.speakers"
    ng-options="person.name + ' ' + person.surname for person in persons"
></select>

我想 as 正在更改比较以确定选择的对象。

这个链接对解决我的问题非常重要:http://jsfiddle.net/maku/TXPJZ/

【讨论】:

    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    相关资源
    最近更新 更多