将多个元素的动态html添加到Angularjs表单,并在按钮单击的范围内使用它

时间:2016-06-29 18:12:21

标签: jquery angularjs angularjs-directive angularjs-scope

我有这样的表格:

HTTP.call('POST', tokenUri, {
    data: {
        "type": 'authorization_code',
        //"client_id": clientId,
        "code": code,
        "redirect_uri" : redirectUri,

    },
    headers: {
        "Access-Control-Allow-Origin" : "*",
        "Access-Control-Allow-Credentials" : "true",
        "Access-Control-Allow-Methods" : "GET,HEAD,OPTIONS,POST,PUT",
        "Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers",
    }
},function(error, response) {
    if ( error ) {
        console.log( error );
    } else {
        console.log( response );
    }
});

这将是更大角度形式的一部分,但我希望用户能够添加多个表单以在表单中添加用户。因此,例如,如果用户单击id为next-user的按钮,我想显示相同的字段,但在保存操作发生时为新用户设置不同的值。

基本上我有两个问题:

  1. 如何在按钮点击角度
  2. 中添加多个html表单,例如此表单
  3. 用户点击保存按钮后如何从多个表单中检索数据,例如上面的那个?

1 个答案:

答案 0 :(得分:0)

执行此操作的纯角度方法是使用控制器函数添加用户和ng-repeat来呈现用户集合,而无需在代码中使用任何DOM操作。这是一个有效的plunk

<强>控制器

app.controller('MainCtrl', function($scope) {
  $scope.users = [{
    username: 'jsmith',
    email: 'jsmith@gmail.com',
    password: '123456',
    name: 'John Smith',
    userType: 'commercial'
  }, {
    username: 'asmith',
    email: 'asmith@gmail.com',
    password: '123456',
    name: 'Alice Smith',
    userType: 'trial'
  }, {
    username: 'dsmith',
    email: 'dsmith@gmail.com',
    password: '123456',
    name: 'David Smith',
    userType: 'commercial'
  }];

  $scope.addUser = function() {
    var newUser = {
      username: '',
      email: '',
      password: '',
      name: '',
      userType: 'commercial'
    };
    $scope.users.push(newUser);
  };
});

<强> HTML

<div ng-repeat="user in users">
  <p class="bold">User {{$index+1}}</p>
  <label>User type:</label>
  <input type="radio" ng-model="user.userType" value="commercial"> Commercial &nbsp;
  <input type="radio" ng-model="user.userType" value="trial"> Trial
  <br/>

  <div>
    <div>
      <label>User Name:</label>
      <input type="text" ng-model="user.username">
    </div>
    <div>
      <label>Email:</label>
      <input type="text" ng-model="user.email">
    </div>
    <div>
      <label>Password:</label>
      <input type="password" ng-model="user.password">
    </div>
    <div>
      <label>Name:</label>
      <input type="text" ng-model="user.name">
    </div>
    <br/>
   </div>
</div>
<div>
   <button class="smallbutton" ng-click="addUser()">Click here to add another user if applicable….</button>
</div>