可以在angular.js上单击按钮添加表中的行吗?

时间:2014-01-22 22:12:00

标签: angularjs

是否可以在单击按钮上的angular.js中添加表格中的行? 我对角度全新,所以也许是研究问题。 我知道使用jquery执行此操作并附加html文本,但如果我有行的html(如部分),有更优雅的方式以角度执行此操作。

3 个答案:

答案 0 :(得分:17)

在angularjs中,你想让你的模型驱动视图,任何DOM操作都应该在指令中发生(你自己的自定义指令或角度库中包含的指令)。

谢天谢地,angular附带了一些非常有用的指令。 ng-repeat非常适合在视图中向表中添加新行的任务。

考虑这个Example

HTML

<body ng-controller="ExampleCtrl">
    <h1>Person List</h1>

    <fieldset>
       <legend>Create Person</legend>
       <input type="text" ng-model="name" placeholder="Name" ><br />
       <input type="number" ng-model="age" placeholder="Age" ><br />
       <input type="text" ng-model="title" placeholder="Title" ><br />
       <button type="button" ng-click="addPerson()">Add Person</button>
    </fieldset>

    <table border="1" cellpadding="10">
       <thead>
         <tr>
           <th>
              Name
           </th>
           <th>
              Age
          </th>
          <th>
              Title
          </th>
          <th>

          </th>
        </tr>
      </thead>
      <body>
         <tr ng-repeat="person in people">
           <td>
             {{ person.name }}
          </td>
          <td>
             {{ person.age }}
          </td>
          <td>
             {{ person.title }}
          </td>
          <td>
             <button type="button" ng-click="removePerson($index)">Remove Person</button>
          </td>
        </tr>
      </body>
    </table>

  </body>

控制器

function ExampleCtrl($scope){
  $scope.people = [
    {name:'Jon', age: 30, title: 'Developer'},
    {name:'Mike', age: 37, title: 'Manager'},
    {name:'Allen', age: 50, title: 'CEO'}
    ];

  $scope.addPerson = function(){
    var person = {
        name: $scope.name,
        age: $scope.age,
        title: $scope.title,
    };

    $scope.people.push(person);
  }; 

  $scope.removePerson = function(index){
    $scope.people.splice(index, 1);
  };  
}

请注意,行ng-repeat="person in people" angular将为我们控制器的<tr>上定义的人员数组中的每个项目呈现$scope

如果我们将另一个人添加到people数组中,angular会在下一个摘要周期内自动在视图中呈现新的<tr>

如果我们从数组中删除一个人,也会发生同样的情况。 DOM元素的所有工作都在ng-repeat指令中隔离。

答案 1 :(得分:4)

todo example就是一个很好的例子,虽然使用li而不是表,但它是相同的概念。

当你是AngularJS的新手时,如果你是一个狂热的jQuery用户,this Q & A可能会有所帮助。

答案 2 :(得分:0)

是的,您可以使用按钮单击将内容添加到表中。无论是否是最佳实践都值得商榷。

基本上,$ scope具有表的模型。单击该按钮时,可以将新数据推送到模型上。

示例:http://codepen.io/calendee/pen/buCHf