【问题标题】:Ng-repeat with dynamic ng-model on input not working使用动态 ng-model 输入的 Ng-repeat 不起作用
【发布时间】:2015-07-04 13:44:46
【问题描述】:

在控制器中,我有一个这样的列表:

scope.data = [ { user: { address: { city: 'Boston'} } } ];

还有一个属性,我有访问对象的名称:

scope.propertyName = 'user.address.city';

在 HTML 中,我有一个 ng-repeat,我在其中放置了一个动态输入来编辑该值。

<div ng-repeat="item in data">
    <input ng-model="item[propertyName]">
</div>

我的问题是:如何将项目的值与 ng-model 绑定?

【问题讨论】:

  • 需要绑定哪个值?
  • 我需要用输入改变列表的值

标签: angularjs


【解决方案1】:

因为ng-repeat,你可以这样做:

<input ng-model="item.user.address.city" />

所以你不需要声明这个:

$scope.propertyName = 'address.city';

Demo

【讨论】:

  • 是的,我需要它。我不知道这是什么价值。他来自数据库。
  • @DudisRoyer 我不明白 - 你有 item.user.address.city 的价值吗?
  • 所以,我需要用输入来编辑这个列表的值。但是,我不知道对象的结构,他来自数据库。
  • 我需要将值与输入绑定,但结构(user.address.city)必须是来自变量的动态。
  • @DudisRoyer 结构将/可能与此有何不同? { user: { address: { city: 'Boston'} } }
【解决方案2】:

您可以使用 compile 创建指令,以间接设置 ng-model:

compile: function(el, attrs) {
      return function(scope, el) {
        el.attr('ng-model', attrs.ngModelItem + '.' + scope[attrs.ngModelRef]);
        $compile(el)(scope);
      };
    }

请在 jsbin 上查看我的示例:

http://jsbin.com/xizucu/edit?html,js,output

【讨论】:

  • 使用这种方式效果很好,但指令保持循环。
  • 我觉得这看起来很慢。当指令的原始属性已被删除以停止循环时,我看到了另一个代码。 $compile 行之前的类似 el.removeAttr('ng-model-item') 的东西
猜你喜欢
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 2022-11-10
  • 2014-02-26
相关资源
最近更新 更多