Angular/Javascript : 按值复制一个简单的数字,没有引用

Angular/Javascript : Copy a simple number by value without reference

我正在尝试复制一个包含 id 的简单范围变量而不引用它。

这是一段代码,展示了我在做什么:

.controller('ctl', function($scope, $rootScope, Resource) {
    var controllerScope = this;

    this.tId = 1;

    /* ... */

    this.addProject = function() {
      this.supportedProjects.push(this.add.project);
      this.supportedProjects = this.supportedProjects.map(function(object) {
        var id = angular.copy(controllerScope.tId);

        if (object.title.title)
          return {
            id: id,
            title: object.title.title,
          };
        else
          return {
            id: id,
            title: object.title,
          };
      });
      this.tId++;
    /* ... */
    };
}

在这种情况下,supportedProjects 中的对象都包含相同的 ID。 那么无参考复制的正确方法是什么?

我不知道发生了什么。

编辑:是我在 map 函数上做错了。

试试这个:

.controller('ctl', function($scope, $rootScope, Resource) {
    var controllerScope = this;

    this.tId = 0;

    /* ... */

    this.addProject = function() {
      this.supportedProjects.push(this.add.project);
      this.supportedProjects = this.supportedProjects.map(function(object) {
        var id = controllerScope.tId + 1;

        if (object.title.title)
          return {
            id: id,
            title: object.title.title,
          };
        else
          return {
            id: id,
            title: object.title,
          };
      });
      controllerScope.tId++;
    /* ... */
    };
}

不确定我是否理解您的意图,但这应该可行:

this.supportedProjects = this.supportedProjects.map(function(object) {

    if (object.title.title)
      object.title = object.title.title;

    return object;
 });