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

Pao*_*aJ. 5 angularjs

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

Jon*_*mbo 17

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

值得一提的是,angular附带了一些非常有用的指令.ng-repeat非常适合在视图中向表中添加新行的任务.

考虑这个例子

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>
Run Code Online (Sandbox Code Playgroud)

调节器

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);
  };  
}
Run Code Online (Sandbox Code Playgroud)

请注意,对于在控制器上定义的人员数组中的每个项目,线条ng-repeat="person in people"角度将呈现一个.<tr>$scope

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

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


Phi*_*ret 4

是的。

todo示例就是一个完美的例子,虽然使用的li并不是表格,但它是相同的概念。

当您刚接触 AngularJS 时,如果您是狂热的 jQuery 用户,那么此问答可能会很有帮助。