使用AngularJS使用一个表单处理多个按钮

时间:2018-01-15 15:28:00

标签: javascript angularjs

我有一个包含不同文本字段和一些按钮的表单。我希望每按一次按钮执行不同的操作,但使用与ng-submit()相同的功能。例如,我想在数据库上实现CRUD操作,并根据从表单中获取的数据执行另一个操作。根据网站上另一篇文章的信息,我设法做到了这一点:

<form name="formUser" ng-submit="cruduser()" role="form">
    // I didn't put the text fields because are irrelevant for this problem
    <div class="form-actions">
        <button type="submit" ng-click="addButton=true" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Add</button>
    </div>

    <br/>

    <div class="form-actions">
        <button type="submit" ng-click="readButton=true" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Read</button>
    </div>

    <br/>

    <div class="form-actions">
        <button type="submit" ng-click="updateButton=true" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Update</button>
    </div>

    <br/>

    <div class="form-actions">
        <button type="submit" ng-click="deleteButton=true" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Delete</button>
    </div>
</div>

这是我的.js文件:

'use strict';

angular.module('admin')
    .controller('AdminController',
        ['$scope', '$rootScope', '$location', 'AdminService',
            function ($scope, $rootScope, $location, AdminService) {

                $scope.cruduser = function() {
                    this.addButton  = false;
                    this.readButton = false;
                    this.updateButton = false;
                    this.deleteButton = false;

                    if(this.addButton) {
                        console.log('Add');
                    }

                    if(this.readButton) {
                        console.log('Read');
                    }

                    if(this.updateButton) {
                        console.log('Update');
                    }

                    if(this.deleteButton) {
                        console.log('Delete');
                    }
                };


                $scope.redirect = function() {
                    session.sessionValue = ' ';
                    window.location = "/#/login";
                }
            }]);

问题是,在使用&#34; false&#34;初始化按钮后,它们仍然保持该值。

1 个答案:

答案 0 :(得分:0)

您可以点击以下按钮,在cruduser功能中传递您想要的操作类型:

<button ng-click = "cruduser('add')"></button>

然后在控制器的cruduser函数中,您可以检查传递的操作:

 $scope.cruduser = function(crudOp) {
     if (crudOp === 'add') {
//do something
  }
}