Angular.js:表单提交操作不是调用

时间:2016-06-28 10:15:37

标签: javascript jquery angularjs forms

我正在尝试在ng-submit事件上提交表单,但表单提交无效。 $ http,$ state,dtoResource是注射 其中dtoResource是修改json数据的工厂。

我的代码如下

的index.html

<!DOCTYPE html>
<html  ng-app="autoQuote">
<head lang="en">
    <meta charset="UTF-8">
    <title>Angular Js DTO mgnt</title>

    <!-- Style sheets -->
    <link href="css/bootstrap.css" rel="stylesheet"/>
    <link href="css/app.css" rel="stylesheet"/>

    <!-- Library Scripts -->
    <script src="js/jquery.js"></script>
    <script src="js/angular.js"></script>   
    <script src="js/angular-ui-router.js"></script>
    <!-- Application Script -->
    <script src="app/app.js"></script>  

    <!-- Services -->
    <script src="common/services/common.services.js"></script>
    <script src="common/services/dtoResource.js"></script>  

    <!-- Controllers -->
    <script src="app/ctrl/autoQuoteCtrl.js"></script>
    <script src="app/ctrl/questionsCtrl.js"></script>

</head>

<body>
    <ul>
      <li><a href="#/">step 1</a>
      <li><a href="#/step2">step 2</a>
    </ul>
    <div class="container"> 


    <div ui-view=""></div>


    </div>
</body>

</html>

step1.html

           电子邮件:       

           

autoQuoteCtrl.js

(function () {
    "use strict";

    angular
    .module("autoQuote")
    .controller("autoQuoteCtrl", ["$http","$state","dtoResource",autoQuoteCtrl]);

    function autoQuoteCtrl($http,$state,dtoResource) {
        console.log('We are in form');
        //self = this;
        // if valid (check form validate true)
        //console.log(dtoResource);
        //call function from your service, and do something with it
        dtoResource.rc1Step1DTO();

        $http({
            method  : 'POST',
            url     : 'api.php',
            data    : { dtoObj: JSON.stringify(prepareAutoQuoteDTO.postAutoQuoteObj) }, // pass in data as strings
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
        })
        .success(function(data) {
            console.log(data);
            if (!data.success) {

            } else {
              // if successful, bind success message to message
              //$scope.message = data.message;
            }
        });
    }

}());

dtoResource.js

(function () {
    "use strict";

    angular
        .module("autoQuote")
        .factory("dtoResource",
                ["$resource",
                 dtoResource]);

console.log('inside dtoResource');
    function dtoResource(){
    var prepareAutoQuoteDTO = {
        postAutoQuoteObj         : $.getAutoQuoteObject(),  
        initializeDriverObj: function(){
            var driverLocObj           = new Driver();
            driverLocObj.PersonInfo    = new PersonInfo();
            driverLocObj.DriverLicense = new DriverLicense();
            driverLocObj.Incident      = new Incident();
            return driverLocObj;
       },
       initializeAppInfo: function(){
           var appInfoLocObj           = new ApplicationInfo();
           appInfoLocObj.Discount      = new Discount();
           return appInfoLocObj;
       },
       /*
       * Initialize Vehicle object for autoQuoteDTO.js
       */
       initializeVehicleObj: function(){
           var vehicleLocObj = new Vehicle();
           return vehicleLocObj;
       },
       /*
       * store session info
       */
       rc1Step1DTO: function(){

            var emailId = $('#save_quote_email').val();
            if (typeof emailId  !== "undefined" && emailId && emailId != '' && emailId != 'Email Address'){
                var email           = new Email();
                email.EmailTypeCd   = 'PRIMARY';
                email.EmailAddress  = emailId;
                this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo =     this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
                this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
                this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
            }
        }
    };
    return prepareAutoQuoteDTO;
}

}());

2 个答案:

答案 0 :(得分:2)

您必须将<ContainerInstance1 data={data1}/> <ContainerInstance2 data={data2}/> ng-app属性添加到父DOM元素。

你无法在ng-controller中调用控制器的实例:)

您应该在控制器中添加特殊方法,并调用该方法。 像这样的东西

ng-submit

你的控制器是这样的

<body ng-app>
 <div ng-controller="autoQuoteCtrl">
  <form ng-submit="onSubmit()">
   ...
  </form>
 </div>
</body>

PS:在这个例子中我使用的是co范围汤。它很容易理解,但它将$ scope与其他属性聚类在一起。现在不建议采用这种方法。在这里阅读更好的方法:http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html

<强>更新

您的代码中有轻微的混淆: 路由重定向到/,由 angular .module("autoQuote") .controller("autoQuoteCtrl", ["$http","$state","dtoResource", function($http, $state, dtoResource) { $scope.onSubmit = function() { alert('hi, I was invoked on form submit'); }; }]); 捕获,但相关模板具有属性questionsCtrl。那么应该使用哪个控制器来响应用户操作?不确定是否有意:)

<强>解

应该像这样调用提交函数

ng-controller=autoQuoteCtrl

我忘记了第一个例子中的 <form ng-submit="onSubmit()"> ,抱歉:)

答案 1 :(得分:0)

HTML

   <div ng-controller="formCtrl">
            <form  name="userForm"  class="well form-search"   >

                <input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" required >
                <input type="email" ng-model="email" class="input-medium search-query" placeholder="Email" required >
                <input type="text" ng-model="message" class="input-medium search-query" placeholder="Message" required >
                <button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)"  ng-disabled="userForm.$invalid">Submit </button>

            </form>
            <pre ng-model="result">
                {{result}}
            </pre>
        </div>

jsfile

var app = angular.module('formExample', []);

app.controller("formCtrl", ['$scope', '$http', function($scope, $http) {
        $scope.url = 'submit.php';

        $scope.formsubmit = function(isValid) {


            if (isValid) {


                $http.post($scope.url, {"name": $scope.name, "email": $scope.email, "message": $scope.message}).
                        success(function(data, status) {
                            console.log(data);
                            $scope.status = status;
                            $scope.data = data;
                            $scope.result = data; // Show result from server in our <pre></pre> element
                        })
            }else{

                  alert('Form is not valid');
            }


        } }]);

click here