【问题标题】:How to dynamic add new element in Angularjs如何在Angularjs中动态添加新元素
【发布时间】:2013-08-08 17:55:23
【问题描述】:

我有一个ng-repeat 来循环我的对象值以查看。 然后我想要一个按钮来将新的空白元素添加到ng-repeat 值的最后一个。

我怎样才能在 Angular 中做到这一点?

我的数据是 json 对象。我试过了

In controller
$scope.objs = {'a': 'a', 'b':'b'};

In view
{{Object.keys(objs).length}};
But nothing show in view.

更新

<div ng-repeat="docstep in docs.docsteps" class="docstep">
   {{docstep.text}}
</div>

然后我想获取对象的长度,这样我就可以在按钮单击时 .length + 1 但我不知道如何获得对象的长度。或者有什么更好的办法?

【问题讨论】:

  • 这是你所有的视图代码还是还有更多?
  • 你的 ng-repeat 是什么样的?
  • @MikeRobinson 我更新了问题
  • @mitch 我更新了问题
  • @sza fiddle 添加,请查看答案的评论

标签: json object angularjs angularjs-ng-repeat


【解决方案1】:

使用 ng-click 将点击处理程序绑定到按钮:

<div ng-repeat="docstep in docs.docsteps" class="docstep">
   <input type="text" value="{{docstep.text}}">
</div>
<button ng-click="addNew()">Add another input</button>
When this button is clicked. It will add another blank input
<br>Which the new input will be docstep3

你的 JS 应该是这样的:

var myApp = angular.module('myApp',[]);
myApp.run(function($rootScope){

    $rootScope.docs = {
        "docsteps" : {
            "docstep1" : {
               "text" : "a"
            },
            "docstep2" : {
               "text" : "b"
            }
        }

    }

    var c = 2; 
    $rootScope.addNew = function(){
        count++;
        $rootScope.docs.docsteps["docstep"+count] = {"text":count}
    }
});

注意:您应该使用 ng-app 为 Angular 定义工作区域并使用 controllers 来驻留模型(docs )并定义视图的行为(addNew)。

【讨论】:

  • docstep1, docstep2 在真实数据中是随机的。我只是为了测试目的而硬编码。顺便问一下,可以检查视图中的长度吗?
  • @vzhen 你需要遍历对象才能知道长度。
  • 我循环了。但我不知道如何获得对象的长度。没有阵列。我试过{{Object.keys(docs).length}} 但没有用。
  • 如果假设您在 docsteps 中有 docstep1 和 docstep2 那么您期望什么?长度 = 2?在上面的代码中,c 指向你看到的对象的长度。您不需要遍历对象。不过,如果您想遍历它,那么您可以在这里查看:stackoverflow.com/questions/5223/…
  • docstep1 和 docstep2 只是测试数据。在现实生活中,我不知道会有多少个文档步骤。所以我必须遍历它并知道长度。您给出的示例是关联数组。
【解决方案2】:

我拿走了你的ng-repeat 并让它工作。请注意,我将您的对象放在 $rootScope 中,但您可以将相同的对象应用于您的 ng-repeat 所在的任何范围。

JS

var myApp = angular.module('myApp',[]);
    myApp.run(function($rootScope){
    $rootScope.docs={docsteps:[{text:'A'},{text:'B'},{text:'C'}]};
});

JSFIDDLE:http://jsfiddle.net/mac1175/Snn9p/

【讨论】:

  • 我将您的小提琴修改为我的实际数据并告诉我我想要什么。请检查一下。 jsfiddle.net/EvsGw/2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
相关资源
最近更新 更多