如何使用数据绑定动态添加元素

时间:2014-11-13 18:07:45

标签: angularjs

所有

我是AngularJS的新手,我的问题是如何在范围内动态添加元素。

像:

<div id="cnt" ng-controller="main">
    <button>Add more</button>
</div>

<script>
  app.controller("main", function($scope){
        $scope.name = "hello";
  });

$("button").on("click", function(){
  var div = $("#cnt").append("div");
  div.html("{{name}}");
});
</script>

应该发生的是新添加的div将具有自动绑定的名称(显示为“hello”)。 但是当我点击按钮时,它只会在其中添加更多带有“{{name}}”的div。

我想知道最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

为什么不使用ng-repeat?您很可能拥有一个需要动态添加的结构化元素。此外,您应该使用ng-click而不是绑定到DOM $(button)。当你有两个按钮用于两个不同目的时会发生什么?

所以你的HTML将是:

<div id="cnt" ng-controller="main">
    <button ng-click="addMore()">Add more</button>

    <div ng-repeat="element in elements track by $index">
        <h1>{{ element.title }}</h1>
        <p>{{ element.body }}</p>
    </div>
</div>

然后你的应用程序将是:

app.controller("main", function($scope) {
    // Initialize the variable as an empty array
    $scope.elements = [];

    // Instead of binding to the button selector, use `ng-click`
    // in your HTML and add the function here
    $scope.addMore = function() {

        // Create a new object with whatever attributes you need 
        var element = {
            title: 'Element Title',
            body: 'Hello World!'
        }
        // Push it to the $scope.elements array
        // ng-repeat will loop through all the elements in the array 
        // It's just like foreach()
        $scope.elements.push(element);
    }
});
相关问题