2016-01-10 52 views
2

我是Angular的新手,想要在列表中創建一個克隆按鈕。具有獨特名稱的克隆對象Angular

當我點擊這個按鈕,它會克隆對象,並添加了一些對象名稱:

「新的測試」 - 將改爲「新的測試(2)」等等...

它需要每次檢查最後3個字母並每次檢查所有對象。

有沒有圖書館這樣做?

+1

可您在此處提供的示例代碼? –

回答

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>