在Angular中具有唯一名称的clone对象

时间:2016-01-10 06:16:53

标签: html angularjs list

我是Angular的新手,正在寻找一种在列表中制作克隆按钮的方法。

单击此按钮时,它将克隆对象并在对象名称中添加一个数字:

"新测试" - 将更改为"新测试(2)"等等...

每次检查最后3个字母并每次检查所有对象。

有没有图书馆这样做?

1 个答案:

答案 0 :(得分:0)

我认为你不需要任何lib。基本上,你需要一个寻找重复的循环。查看示例:



angular.module('myApp', [])
.controller('MyCtrl', function($scope){
  $scope.items = ['Sample item'];
  $scope.suggestedNewName = 'Sample item';
  var isNameOccupied = function(name) {
    return $scope.items.indexOf(name) >= 0;
  };
  $scope.addNewItem = function(){
    var suggestedName = $scope.suggestedNewName;
    var newName = suggestedName;
    for (var i = 2; isNameOccupied(newName); i++) {
      newName = suggestedName + " (" + i + ")";  
    }
    $scope.items.push(newName);
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <form ng-controller="MyCtrl" ng-submit="addNewItem()">
    <ul>
      <li ng-repeat="item in items">{{ item }}</li>
    </ul>
    <label>Suggested name for new item:</label>
    <input type="text" ng-model="suggestedNewName">
    <button type="submit">Add new item!</button>
  </form>
</div>
&#13;
&#13;
&#13;