angular.copy从JS对象中删除了frunction。任何替代品?

时间:2017-04-14 10:07:39

标签: javascript angularjs

我将一些js变量保存为:

{
            "column": {
                "stacking": 'normal',
                "dataLabels": {
                    "enabled": true,
                    "color": 'white',
                    "formatter": function() {
                        if (this.y != 0) {
                            return this.y + '%';
                        } else {
                            return null;
                        }
                    },
                    "style": {
                        "textShadow": '0 0 2px black'
                    }
                }
            }
        }

当我使用angular.copy(varName)复制此变量时,在角度控制器内部,格式化程序函数将被删除。

很可能angular.copy不能很好地与函数配合使用。还有什么其他选择?

我需要更改 varName 属性和值,如果我在同一个控制器中多次执行它,它会绑定。

jQuery.extend(true,{},varName)执行相同的操作

编辑: 我错了,angular.copy工作得很好。 我的错误是我正在为对象做一个JSON.stringify和JSON.parse,并删除了该函数。

2 个答案:

答案 0 :(得分:0)

不,angular.copy不会删除功能。



var obj = {
  "column": {
    "stacking": 'normal',
    "dataLabels": {
      "enabled": true,
      "color": 'white',
      "formatter": function() {
        if (this.y != 0) {
          return this.y + '%';
        } else {
          return null;
        }
      },
      "style": {
        "textShadow": '0 0 2px black'
      }
    }
  }
}

console.log(angular.copy(obj))

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

angular.copy无法复制formatter属性的一种情况是,formatter可枚举属性描述符设置为false

你可以这样试试:

var yourObj = {
  "column": {
    "stacking": 'normal',
    "dataLabels": {
      "enabled": true,
      "color": 'white',
      "formatter": function() {
        if (this.y != 0) {
          return this.y + '%';
        } else {
          return null;
        }
      },
      "style": {
        "textShadow": '0 0 2px black'
      }
    }
  }
}

console.log(angular.copy(yourObj)); //formatter property is there.

Object.defineProperty(yourObj, "formatter", {
  value: function() {
        if (this.y != 0) {
          return this.y + '%';
        } else {
          return null;
        }
      },
  enumerable: false,
  writable: true,
  configurable: true
});

console.log(angular.copy(yourObj)); //formatter property is not there.

如果您尚未修改formatter属性的属性描述符,angular.copy应该有效。