【问题标题】:Using ui-select2 with ng-repeat does not set the model correctly使用 ui-select2 和 ng-repeat 不能正确设置模型
【发布时间】:2014-02-26 18:25:39
【问题描述】:

首先,一些背景:

使用ui-select2 时,您必须在select2 配置对象中提供initSelection 函数。否则,您将收到错误消息(但功能不会受到影响。一切仍将按预期工作)。

为了说明,请参阅this plunkr。当您从下拉菜单中选择一个项目时,它会起作用,但您会收到以下错误:

错误:如果未定义 initSelection(),则无法调用 val()

initSelection 添加一个空函数可修复该错误。您可以在上面的 plunkr 中取消注释以查看。


问题:

using ui-select2 in conjunction with ng-repeat 时,它只是不更新​​模型。

控制器:

// for this demo, `users` is injected into the controller
$scope.users = users.slice(0, 2);

$scope.select2Config = {

    placeholder: 'Select User...',

    query: function ( options )
    {
        // `users` in this demo is injected into the controller.
        // in the real world this would be an ajax request
        options.callback({ results: users });
    },

    // Without initSelection, I get the above error.
    // Regardless, the model isn't updated.
    initSelection: angular.noop,

    formatSelection: select2format,

    formatResult: select2format,


};

function select2format ( user )
{
    return user.first + ' ' + user.last;
}

查看:

<ul> 
   <li ng-repeat="user in users">
       <input type="text" ng-model="user" ui-select2="select2Config">
   </li> 
</ul>

从下拉列表中选择项目时,模型不会更新。如果配置中没有initSelection,我会收到上述错误,但添加它仍然不会更新模型。

Here's a plunkr demonstrating the above.


问题:

如何让ui-select2 更新ng-repeat 中的模型?

【问题讨论】:

    标签: javascript angularjs angularjs-ng-repeat angular-ui jquery-select2


    【解决方案1】:

    尝试使用继承:

    http://plnkr.co/edit/jyJaYU4DQX1LROD6nQaw?p=preview

    另外,我在 ng-repeat 上调用了“用户中的用户”,但随后还将 ng-model 设置为“用户”。我不知道为什么。

    至于 initSelection 行为,我没有答案。


    编辑

    我更新了 plunker。 ng-repeat 指令创建了一个新的范围 - true,但它的所有子项(或重复项)都是兄弟。您已将“user”(由 ng-repeat 定义/嵌入)绑定到每个 select 的 ng-model(并期望如果您更改模型,“users”数组将被更新)。

    我相信 ng-repeat 是一种单向绑定 top down

    因此,我展示的内容是正确的,但诚然是懒惰的。我将两个选择绑定到同一个模型,但我也很容易使用 $index 将它们绑定到“选定”对象上的单独属性。

    要点是:如果你想要双向绑定,那就写一个新的指令,但做一些类似于我展示的事情会更容易。

    PS:实际上,我填充了一个“查找”对象,其中包含一些用于选择/下拉的数组,并使用一个名为“用户”的单独对象来保存用户选择的内容。这几乎是从(旧的)文档中提取出来的。

    【讨论】:

    • 您没有使用中继器范围。您在作用域上有一个单独的 selection 对象,您没有充分的理由只有 2 个 select2 实例。改变其中一个会改变另一个。您的演示甚至与我上面概述的内容无关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多