角度1:为新创建的对象添加新ID

Angular 1: Add new ID to newly created objects

本文关键字:对象 添加 ID 创建 角度 新创建      更新时间:2023-09-26

我有一个只有1个输入字段的简单表单。对于每个输入,都会创建一个新对象。这是我添加新对象的方法。我正在寻找一种有角度的方式来为这些对象添加ID,你有什么建议?

$scope.addToDoItem = function(){
  var toDoItems = $scope.toDoItems;
  var newToDoItem = {
    "id" : // id should be generated here
    "content" : $scope.toDoItem,
    "createdAt" : Date.now()
  }
  toDoItems.push(newToDoItem);
  ls.set("toDoData", toDoItems);
  $scope.toDoItem = "";
};

视图:

  <form>
    <input type="text" ng-model="toDoItem">
    <input type="submit" ng-click="addToDoItem()">
  </form>

我不认为有"棱角分明的方法"可以做到这一点。

但是,当前createdAt值使用毫秒,因此Id也可以使用相同的值。如果你没有可以更频繁地添加新价值的应用程序,你就会有你独特的价值:

var currentDate = Date.now();
var newToDoItem = {
    "id" : currentDate
    "content" : $scope.toDoItem,
    "createdAt" : currentDate
}

不利的一面是ID值会很大,而且它们不会按顺序排列。如果您希望值为1、2、3等,那么您可以在控制器中为最大ID创建变量,并使用它来增加值:

var maxId = 0;
//if you need to restore maxId you can use
//var maxId = $scope.toDoItems.reduce(function(max,cur){return Math.max(max,cur.id); },0);
$scope.addToDoItem = function(){
  var toDoItems = $scope.toDoItems;
  maxId++;
  var newToDoItem = {
    "id" : maxId,
    "content" : $scope.toDoItem,
    "createdAt" : Date.now()
  }
  toDoItems.push(newToDoItem);
  ls.set("toDoData", toDoItems);
  $scope.toDoItem = "";
};

如果你想要一个随机散列,你也可以做这个

$scope.addToDoItem = function() {
var toDoItems = $scope.toDoItems;
var newToDoItem = {
    "id": function randString() {
        var x = 32; // hashlength
        var s = "";
        while (s.length < x && x > 0) {
            var r = Math.random();
            s += (r < 0.1 ? Math.floor(r * 100) : String.fromCharCode(Math.floor(r * 26) + (r > 0.5 ? 97 : 65)));
        }
        return s;
    },
    "content": $scope.toDoItem,
    "createdAt": Date.now()
}
toDoItems.push(newToDoItem);
ls.set("toDoData", toDoItems);
$scope.toDoItem = "";
};