【问题标题】:HTML parsed through $compile, ng-model not binding in isolation for ng-repeat通过 $compile 解析的 HTML,ng-model 没有单独绑定到 ng-repeat
【发布时间】:2016-04-02 12:22:30
【问题描述】:

我正在构建一个允许动态构建表单的 Angular 模块。

当元素被选中时,HTML 被添加到模型中。该模型附加到 ng-repeat 元素。

<div ng-repeat="item in list1 track by $index">
  <div compiledom="item.content"></div>
</div>

所以模型中的item 可能如下所示:

{
 'title': 'Full-Column Text',
 'drag': true,
 'inputValue': '',
 'content': '<div class="small-12 columns"><input type="text" dynamic-model="$index" placeholder="Full Width Text" /></div>'
}

我正在使用自定义指令来编译提供给模型的 HTML。

.directive('compiledom', function($compile) {
 return function(scope, element, attrs) {
  scope.$watch(
    function(scope) {
      return scope.$eval(attrs.compiledom);
    },
    function(value) {
      element.html(value);
      $compile(element.contents())(scope);
    }
  );
 }
})

并使用第二个指令将模型数据绑定到该 HTML 中的输入字段。

.directive('dynamicModel', function($compile) {
 return function(scope, element, attrs) {
  scope.$watch(attrs.dynamicModel, function(dynamicModel) {
    if (attrs.ngModel || attrs.ngModel == dynamicModel || !dynamicModel) return;

    element.attr('ng-model', 'item.inputValue'); <---------- bound here

    if (dynamicModel == '') element.removeAttr('ng-model');
    element.unbind();
    $compile(element)(scope);
  });
 }
})

我的问题是,我在输入字段中输入的任何内容都会被放置到每个输入元素中。出于某种原因,似乎单个item.inputValue 会反映到同一类型的每个item。该模型是有约束力的,但我在 ng-repeat 中破坏了一些使其保持隔离的东西。

例如,如果我有两个“全列文本”输入,如果一个设置为“ABC”,则两个都设置为“ABC”。如果我也有 2 个“半列文本”输入,它们将保持未设置,直到我将其中一个设置为“DCE”——然后它们都设置为“DCE”。

将很快分享指向该问题的演示/示例的链接。

【问题讨论】:

    标签: angularjs angularjs-ng-repeat angular-ngmodel angular-directive


    【解决方案1】:

    事实证明,我的指令很好。

    当我添加到我的模型中时,我使用的是.slice。这导致了反射问题。使用angular.copy 做了一个真正的克隆,允许我正在寻找的隔离。

    $scope.list1[x] = angular.copy($scope.list5[x]);

    【讨论】:

      猜你喜欢
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 2017-11-19
      • 2015-07-24
      • 2014-07-12
      • 1970-01-01
      相关资源
      最近更新 更多