如何以AngularJS表单发送发布数据以播放框架控制器



我在我的Web应用程序(播放框架2.2.1& scala)上有一个用Ajax和AngularJS显示的客户列表。它运行良好,现在我想在我的列表中动态添加一个新客户,并使用我制作的JS弹出式(使用JQuery UI)。

我首先搜索如何在html/angularJS表单发送的浏览器数据上显示,但是当我单击我的提交按钮时,什么都没有发生...我不知道为什么,其他AngularJS操作有效。

这是我的代码:

  • javascript

    function AddCustomerController($scope) {
        $scope.add = function() {
            $scope.customers.push({id: $scope.email, phone: $scope.phone, isActivated: $scope.activation, name: $scope.name, roleType: $scope.roleType});
        }
    }
    
  • html

    <div id="dialogAddCustomer" title="title" ng-controller="AddCustomerController">
        <label id="dialNewCustomerName">Add Customer</label>
        <label class="lblPopUp">Email</label>
        <input type="text" id="dialNewCustomerEmail" class="form-control" ng-model="email" />
        <label class="lblPopUp">Phone Number</label>
        <input type="text" id="dialNewCustomerPhone" class="form-control" ng-model="phone" />
        <label class="lblPopUp">Customer Activated ?</label> <br />
        <input type="radio" name="activation" id="dialNewCustomerYes" value="1" ng-model="activation" /> Yes
        <input type="radio" name="activation" id="dialNewCustomerNo" value="2" ng-model="activation" /> No
        <label class="lblPopUp">Name</label>
        <input type="text" id="dialNewCustomerName" class="form-control" ng-model="name" />
        <label class="lblPopUp">Role Type</label> <br />
        <select class="form-control" ng-controller="RoleTypesController">
            <option ng-repeat="roleType in roleTypes" value="{{roleType.id}}" ng-model="roleType">{{roleType.name}}</option>
        </select>
        <br />
        <button class="btn btn-default" type="submit" ng-click="add()">Validate</button>
    </div>
    

第二,我不知道如何正确地将数据推向我的控制器(我已经在网络上搜索)以将新客户插入数据库中。

有任何想法或提示?

也许您应该将AddCustomerController添加到HTML,或将add()函数移至CustomerController

您还应该将customer对象放入范围,然后将单个字段添加到其范围内,然后通过customer.emailcustomer.phone等访问它。这将有助于防止范围问题,并使控制器代码变得更加简单。

另外,这与Play无关,因为您不向服务器发送任何数据(在Angular的文档中查看$ http有关如何执行此操作)。

从未将任何东西发送到服务器,因为代码永远不会指示AngularJS发送任何内容。

您的add功能仅修改本地范围,并且不调用$http.post()

您可能会用HTML术语来思考太多,而用Angularjs的话来说还不够。使用Angular,您无需具有形式;它可以方便 - 特别是用于验证 - 但不是必需的。该模型是关键,无论有没有形式。

通常,我建议让您的 input s修改对象的部分,所以不要:

<input type="text" ng-model="email" />
<input type="text" ng-model="phone" />
<button type="submit" ng-click="add()">Add</button>

做:

<input type="text" ng-model="customer.email" />
<input type="text" ng-model="customer.phone" />
<button type="submit" ng-click="add(customer)">Add</button>

控制器然后类似:

function AddCustomerController($scope, $http) {
    $scope.customer = {};
    $scope.add = function(newCustomer) {
        // this assumes newCustomer has been validated
        $http.post('/api/customers', newCustomer); // TODO: handle response
    }
}

作为旁注,您进入角度的越多,您需要jQuery和jQuery UI的越少 - 我有一个规则,即页面是jQuery还是Angular,但绝不是两者兼而有之。YMMV。

最新更新