如何格式化我的 AngularJS 数据模型?

How do I format my AngularJS data model?

您好,我刚开始 angular,我正在努力寻找答案,我确信这是一件很简单的事情。

我目前正在获取一些输入框的值并将它们推送到我的范围内。这是创建一个长 'array' 例如:

['data-1','data-2','data-3']

我想按以下方式格式化我的数据

$scope.data = [
    {
      'header1':  'data1-1',
       'header1': 'data1-2',
       'header1': 'data1-3'
    },
    {
         'header1': 'data2-1',
         'header1': 'data2-2',
         'header1': 'data2-3'
    }

]

这是我目前的职能。

$scope.createRow = function(){
    angular.forEach(angular.element("input"), function(value, key){
            $scope.td.push($(value).val());
        });

}

任何帮助或指点将不胜感激,因为我刚刚开始了解 angular 方式

这样做并不难...但在我给你一枪搬起石头砸自己的脚之前,我想先解释一下为什么你想要其他格式的结构是有益的提到。您似乎有很多数据重复,这始终是一个危险信号。

现在对于代码,您只需要在将对象推送到数组之前创建对象,例如:

$scope.createRow = function(){
    angular.forEach(angular.element("input"), function(value, key){
        var obj = {
            "header1": val + "-1",
            "header2": val + "-2"
        };

        $scope.td.push(obj);
    });
}

编辑:

好的,您正在尝试向 table 添加新行。首先,你不应该做 angular.forEach,而是 HTML 中的那些输入元素应该绑定到现有的范围对象,比如:

// obviously use better names than Input1Value
// I am here just giving you example
$scope.bindData = {
    Input1Value: null,
    Input2Value: null
}; 

// in HTML you will do
// <input ng-model="bindData.Input1Value" />
// <input ng-model="bindData.Input2Value" />

既然你已经消除了那个令人讨厌的 angular.forEach 你需要有某种事件处理程序,例如当用户单击你想要将此对象添加到数组中的按钮时 table 是数据绑定的。只要确保在将 $scope.bindData 对象添加到数组时克隆它即可。

$scope.createRow = function(){
    var newRowData = $scope.cloneObject($scope.bindData);
    $scope.td.push(newRowData);
}

// http://heyjavascript.com/4-creative-ways-to-clone-objects/
// 
$scope.cloneObject = function(objToClone) {     
    var newObj = (JSON.parse(JSON.stringify(objToClone)));
}

关闭此答案 - 请记住,如果您发现自己直接引用 Javascript 中的 HTML DOM 元素和 AngularJS - 你做错了什么。这是一个需要改掉的坏习惯,尤其是如果你来自 jQuery 背景(怎么没有?),那里的一切都是 $("#OhHiThere_ElementWithThisId).

显然 Whosebug 上关于此主题的主线程是这个:

“Thinking in AngularJS” if I have a jQuery background?

但是我发现它过于理论化,所以 Google 周围你可能会找到更好的概述,例如:

jQuery vs. AngularJS: A Comparison and Migration Walkthrough