2016-01-27 2 views
1

Я изучаю угловые js. Я просто хочу очистить поля формы и показать успешный div внутри http then().Доступ к элементам формы и div от Angular Promise

this.formSubmitted = false; 
this.successs = false; 

myResumeApp.controller("FormController",['$http', function($http){ 
    this.formSubmit = function(contactForm) { 
    this.formSubmitted = true; 
    if(contactForm.$valid) 
    { 
     $http({ 
       method: 'post', 
       url: 'http://jerrythimothy.is-great.net/mailme.php', 
       data: $.param({ 
        fname : this.fname, 
        email : this.email, 
        content : this.content 
       }), 
       headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
      }).then(function successCallback(response) { 
       this.successs = true; 
       // this callback will be called asynchronously 
       // when the response is available 
       }, function errorCallback(response) { 
       // called asynchronously if an error occurs 
       // or server returns response with an error status. 
       });// JavaScript Document 
     } 
    }; 
}]); 



<div class="container" ng-controller="FormController as formCtrl"> 
    <h2>Contact me</h2> 
    <div ng-show="formCtrl.successs" class="alert alert-success fade in"   style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;">Thank you for contacting me. I will be in touch with you shortly.</div> 
    <form role="form" name="contactForm" novalidate ng-submit="formCtrl.formSubmit(contactForm)"> 

Пожалуйста, дайте мне знать, что-то не так с моим кодом или любыми другими предложениями. Элемент управления входит в блок then(). Но мне нужно знать, как получить доступ к элементу успеха и очистить поля формы.

спасибо.

+0

узнавайте JavaScript первый – Yerken

ответ

0

Вместо this, используйте $scope (и добавить его зависимостей). Правильно знаю, что ваше свойство successs присваивается различным объектам (функция окна и обратного вызова). Код

Контроллер:

myResumeApp.controller("FormController",[ 
    '$scope', 
    '$http', 
    function($scope, $http){  
     $scope.successs = false; 
     $scope.formSubmitted = false; 
     $scope.msg = {}; 
     $scope.formSubmit = function(contactForm) { 
      $scope.formSubmitted = true; 

      if(contactForm.$valid) 
      { 
       $http({ 
        method: 'post', 
        url: 'http://jerrythimothy.is-great.net/mailme.php', 
        data: $.param({ 
         fname : $scope.msg.fname, 
         email : $scope.msg.email, 
         content : $scope.msg.content 
        }), 
        headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
       }).then(function successCallback(response) { 
        $scope.successs = true; 
        $scope.msg = {}; 
        // this callback will be called asynchronously 
        // when the response is available 
        }, function errorCallback(response) { 
        // called asynchronously if an error occurs 
        // or server returns response with an error status. 
        });// JavaScript Document 
      } 
     }; 
    } 
]); 

HTML код:

<div class="container" ng-controller="FormController as formCtrl"> 
<h2>Contact me</h2> 

<div ng-show="successs" 
class="alert alert-success fade in"   
style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;"> 
    Thank you for contacting me. I will be in touch with you shortly. 
</div> 
<form role="form" name="contactForm" novalidate ng-submit="formSubmit(contactForm)"> 
    <input type="text" name="name" ng-model="msg.fname" /> 
    <input type="text" name="email" ng-model="msg.email" /> 
    <input type="text" name="content" ng-model="msg.content" /> 
    <input type="submit" value="submit" /> 
</form> 
+0

работает как шарм !!! Спасибо. MayI знаю, когда использовать это и когда использовать $ scope? –

0

Вы должны уметь это обрабатывать в successCallback.

... .then(function successCallback(response) { 
      this.successs = true; 
      contactForm.reset() 
      }, ... 

Кроме того, я не думаю, что this внутри successCallback такой же, как в строке, где инициализирует this.formSubmitted = false;...

Смежные вопросы