【问题标题】:Convert delimited string and an array of objects转换分隔字符串和对象数组
【发布时间】:2014-07-25 21:02:34
【问题描述】:

如何通过数据绑定在分隔字符串和对象数组之间进行转换?

ng-list 将使用字符串数组。但是我有一个对象数组,我想在其中分隔文本属性,以便可以编辑数组中的文本。

适用于字符串数组

$scope.arrayStrings = ["one", "two", "three"];
<textarea ng-model="arrayStrings" ng-list="&#10;" ></textarea>

我怎样才能让它与对象一起工作

$scope.arrayObjects = [{
  text: "one",
  selected: true
}, {
  text: "two",
  selected: true
}, {
  text: "three",
  selected: true
}];
<textarea ng-model="arrayObjects" ng-list="&#10; | text" ></textarea>

Here's a demo in plunker


我有一个可能的想法是在字符串数组上使用 ng-list,然后将其映射到对象数组。每当字符串数组发生更改时,使用$watch 更新对象数组。但是,这仍然不足,因为每次数组更新时它都会覆盖对象上的任何其他属性。 (以前的 plunker 版本中的演示)

$scope.$watch('arrayStrings', function() {
  $scope.arrayObjects = $scope.arrayStrings.map(function(s){
    return {
      text: s,
      selected: true
    }
  });
})

更新:

即使使用Krzysztof's suggestion,使用ng-list 时似乎仍然存在问题:

toString: function() { return s }

覆盖toString 方法在最初显示时有助于对象集,但只要您键入任何内容,ng-list 就会将对象集转换回字符串数组,因为此时toString 还没有出现发挥作用。

澄清我想要做什么。我真的想要一个对象列表,带有可编辑的标题,也可以选择。即使标题已更改或已添加项目,我也想保留选择。

Here's another plunker to demonstrate

【问题讨论】:

标签: javascript arrays angularjs angular-nglist


【解决方案1】:

toSting()

JavaScript 使用方法toString() 来表示文本值。默认情况下,toString() 方法由 Object 的后代继承。如果自定义对象中没有重写此方法,则 toString() 将返回 "[object type]",其中 type 是对象类型。

覆盖 toSting()

方法 `toSting() 几乎可以像 JavaSctript 中的所有内容一样被覆盖

$scope.arrayObjects = $scope.arrayStrings.map(function(s){
    return {
        text: s,
        selected: true,
        toString: function() {
            return '{text: "' + s + '"}' // this will be returned instead of [object Object]
        }
    }
});

【讨论】:

  • 感谢您的建议。虽然,只要我输入任何内容,它仍然会覆盖列表。我用澄清更新了我的问题。我认为ng-list 正在转换每个逗号分隔的条目,而不管toString 方法是什么。
【解决方案2】:

虽然Krzysztof's suggestion 很有帮助,但我无法完全让绑定与ng-list 一起工作,因为ng-list 将始终将对象数组转换为字符串数组,从而覆盖我在范围内的任何对象.

在这种情况下,最简单的做法是从 ng-list 升级到像大多数标记库一样具有完整对象支持的东西:

我这样实现了 ngTagsInput:

HTML

<tags-input ng-model="arrayObjects" display-property="text"></tags-input>

JavaScript

$scope.arrayObjects = [
  { "text": "one"   , "selected": false },
  { "text": "two"   , "selected": false },
  { "text": "three" , "selected": false }
];

这样,每个对象都被赋予了它自己的元素,其中显示了文本属性,并且它们都被格式化在一起以存在于输入中。更改一个对象只会更新该单个元素

Demo in Pluner

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2021-12-07
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多