0

Working on my first small AngularJS App I'm facing problems with a form submit. I worked trough the CodeSchool course and figured the most out by myself, but this form submit thingy... well I just don't get where I'm wrong so that's why it would be nice if you could show me the right solution, so I can go on.

Project: A simple Workout List where you can list all the training sessions you had. This is my HTML, Element 3 is the problem:

   <header class="wob-masthead container-fluid">
        <div class="row">
                <div class="col-md-6" ng-init="tab = 1">
                        <ul class="nav nav-pills">
                                <li ng-class="{ active:tab === 1 }"><a href ng-click="tab = 1">Overview</a></li>
                                <li ng-class="{ active:tab === 2}"><a href ng-click="tab = 2">Stats</a></li>
                                <li ng-class="{ active:tab === 3 }"><a href ng-click="tab = 3">New</a></li>
                        </ul>
                </div>
                <div class="col-md-6">
                        <form class="navbar-form pull-right" role="search">
                                <div class="form-group">
                                        <input type="text" class="form-control" placeholder="Search">
                                </div>
                                <button type="submit" class="btn btn-default">Search</button>
                        </form>
                </div>
        </div>
    </header>
    <section class="wob-main mainlist container" id="headjump">



     <!--- ==========================================
    Element 1: Overview
    ============================================= -->



    <div class="subsite" ng-show="tab === 1">
        <div class="headico"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></div>
        <h1>WorkoutBuddy</h1>
    <div class="table-responsive" ng-controller="ListController as listing">           
    <table class="table table-hover">
    <thead>
        <tr>
                <th  class="col-md-2">Date</th>
                <th  class="col-md-8">Type</th>
                <th  class="col-md-1">Repeat</th>
                <th  class="col-md-1">Time</th>
        </tr>
    </thead>
    <tbody ng-controller="ListController as listing">
        <tr ng-repeat="wo in listing.sessions">
                <td>{{wo.date | date:'dd/MM/yyyy'}} </td>
                <td>{{wo.name}}</td>
                <td>{{wo.repeat}}</td>
                <td>{{wo.time}} Minutes</td>
        </tr>
    </tbody>
    </table>
        </div>
    </div>


    <!--- ==========================================
    Element 2: Stats
    ============================================= -->




    <div class="subsite" ng-show="tab === 2">
        <div class="headico"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></div>
        <h1>Stats</h1>          
    <!-- Ende Subsite -->
    </div>



    <!--- ==========================================
    Element 3: New
    ============================================= -->


    <div class="subsite" ng-show="tab === 3">
        <div class="headico"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></div>
        <h1>New</h1>

    <div class="table-responsive" ng-controller="ListController as listing">           
    <table class="table table-hover">
    <thead>
        <tr>
                <th  class="col-md-2">Date</th>
                <th  class="col-md-8">Type</th>
                <th  class="col-md-1">Repeat</th>
                <th  class="col-md-1">Time</th>
        </tr>
    </thead>
    <tbody ng-controller="ListController as listing">
        <tr ng-repeat="wo in listing.sessions | limitTo:2">
                <td>{{wo.date | date:'dd/MM/yyyy'}} </td>
                <td>{{wo.name}}</td>
                <td>{{wo.repeat}}</td>
                <td>{{wo.time}} minutes</td>
        </tr>
    </tbody>
    </table>
        </div>

    <form name="WorkoutForm" ng-controller="EntryController as entryCtrl">

    <blockquote>
        <h3>Last Workout:</h3>
        <strong>{{entryCtrl.wo.name}}</strong><br>
        <small>am: {{entryCtrl.wo.date}}</small><br>
        {{entryCtrl.wo.repeat}} repeats in {{wo.time}} minutes.
    </blockquote>


        <input ng-model="entryCtrl.wo.date" type="date" placeholder="date" />
        <input ng-model="entryCtrl.wo.name" type="name" placeholder="name"  />
        <input ng-model="entryCtrl.wo.repeat" type="repeat" placeholder="repeat"  />
        <input ng-model="entryCtrl.wo.time" type="time" placeholder="time"  />
        <input type="submit" value="Add" />
    </form>
    <!-- Ende Subsite -->
    </div>
    </section>

I styled it with Bootstrap and this is my app.js:

    (function(){    
    var app = angular.module('wobuddy', [ ]);

    app.controller('ListController', function(){
        this.sessions = wos;       
    });

    var wos = [
    {
        name: 'Squat',
        date: '01.01.2015',
        repeat: 50,
        time: 10
    },
    {
        name: 'Push Ups',
        date: '01.01.2015',
        repeat: 50,
        time: 10
    }
    ];

    })();

Switching between the sections using the nav works pretty fine and also printing out the data-elements in the table, but when I push submit nothing happens - really hope you can help me to learn :-)

6
  • What are you trying to make it do? Commented Mar 6, 2015 at 9:57
  • When I click submit the new entry should be added to the list (var wos) and added to the table. Commented Mar 6, 2015 at 9:58
  • Have you got code for ReviewController? Commented Mar 6, 2015 at 10:01
  • just updated the code to EntryController as entryCtrl Commented Mar 6, 2015 at 10:08
  • Ok, then have you got code for EntryController? Commented Mar 6, 2015 at 10:09

4 Answers 4

2

You need to make an EntryController that will add a new object to the end of the wos collection. Something like this:

app.controller('EntryController', function($scope) {
  $scope.wo = {};
  $scope.submit = function() {
    wos.push($scope.wo);
    $scope.wo = {};  // Clear the form fields
  };
});

Then your HTML for that section could look something like this:

<form name="WorkoutForm" ng-controller="EntryController">
    <blockquote>
        <h3>Last Workout:</h3>
        <strong>{{wo.name}}</strong><br>
        <small>am: {{wo.date}}</small><br>
        {{wo.repeat}} repeats in {{wo.time}} minutes.
    </blockquote>

    <input ng-model="wo.date" type="date" placeholder="date" />
    <input ng-model="wo.name" type="name" placeholder="name"  />
    <input ng-model="wo.repeat" type="repeat" placeholder="repeat"  />
    <input ng-model="wo.time" type="time" placeholder="time"  />
    <button ng-click="submit()">Add</button>
</form>

Notice that it's more usual for a controller to communicate data to the template via the $scope object rather than via the controller object itself.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you very much! This helps me a LOT, it's now working (I know it's not the best solution, it's just that I'm learning it and each little progress helps)
:D yeah I know, it works like a breeze, I was just referring to your 'communicate data to the template via $scope'-comment. After all I still think the best way to learn a new technique is building something, reading and asking - so thank you very much for helping!
Oh, right. Just to be clear, this code is an example of communicating from the controller to the template via the $scope.
1

By looking at you form HTML, I think you missed the name attribute inside your form and also ng-submit directive is missing which will gets called after a submit form. Do check form validation inside controller using $valid() method and perform post else give alert to user.

HTML

<form name="workoutForm" ng-controller="ReviewController as reviewCtrl" ng-submit="submit(workoutForm, entryCtrl.wo)">

    <blockquote>
        <h3>Last Workout:</h3>
        <strong>{{entryCtrl.wo.name}}</strong>
        <br>
        <small>am: {{entryCtrl.wo.date}}</small>
        <br> {{entryCtrl.wo.repeat}} repeats in {{wo.time}} minutes.
    </blockquote>


    <input name="date" ng-model="entryCtrl.wo.date" type="date" placeholder="date" />
    <input name="name" ng-model="entryCtrl.wo.name" type="name" placeholder="name" />
    <input name="repeat" ng-model="entryCtrl.wo.repeat" type="repeat" placeholder="repeat" />
    <input name="time" ng-model="entryCtrl.wo.time" type="time" placeholder="time" />
    <input type="submit" value="Add" />
</form>

Controller

$scope.submit = function(workoutForm, item){
   if(workoutForm.$valid)
     //then make $http.post by sending item values
   else
     //show error
};

Comments

1

UPDATE

<html ng-app='demoApp'>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
<body>


<form ng-controller="validationCtrl">
    <input type="text" placeholder="Name...." ng-model="user.name"/>
    <input type="text" placeholder="Password...." ng-model="user.pass"/>
    <input type="text" placeholder="Mobile...." ng-model="user.mo"/>
    <input type="submit" ng-click="alldata(user)"/>
</form>
<script>
//This is controller
var app = angular.module('demoApp', []);
app.controller('validationCtrl', function($scope) {

   $scope.alldata=function(user)
   {
    alert(JSON.stringify(user));
   }
});
</script>

</body>
</html>

Comments

0

You can also use this method, and Your form shoud be like

<form method="post" name="sentMessage" id="my_contact" novalidate="novalidate">
      <div class="control-group">
        <div class="form-group floating-label-form-group controls mb-0 pb-2">
          <label>Name</label>
          <input class="form-control" id="name" type="text" name="name" placeholder="Name" required="required" data-validation-required-message="Please enter your name.">
          <p class="help-block text-danger"></p>
        </div>
      </div>
      <div class="control-group">
        <div class="form-group floating-label-form-group controls mb-0 pb-2">
          <label>Email Address</label>
          <input class="form-control" id="email" type="email" name="email" placeholder="Email Address" required="required" data-validation-required-message="Please enter your email address.">
          <p class="help-block text-danger"></p>
        </div>
      </div>
      <div class="control-group">
        <div class="form-group floating-label-form-group controls mb-0 pb-2">
          <label>Phone Number</label>
          <input class="form-control" id="phone" type="tel" name="phone" placeholder="Phone Number" required="required" data-validation-required-message="Please enter your phone number.">
          <p class="help-block text-danger"></p>
        </div>
      </div>
      <div class="control-group">
        <div class="form-group floating-label-form-group controls mb-0 pb-2">
          <label>Message</label>
          <textarea class="form-control" id="message" rows="5" name="Message" placeholder="Message" required="required" data-validation-required-message="Please enter a message."></textarea>
          <p class="help-block text-danger"></p>
        </div>
      </div>
      <br>
      <div id="success"></div>
      <div class="form-group">
        <a href="javascript:void(0)" (click)="send_query()" class="btn btn-primary btn-xl" id="sendMessageButton">Send</a>
      </div>
    </form

import jquery as below npm install jquery using CLI

import * as $ from 'jquery';

send_query() function will be

send_query() {
var data = $("#my_contact").serializeArray();
var indxarr = {};
$.each(data,function(i,v){
  indxarr[v['name']] = v['value'];
});
data = JSON.parse(JSON.stringify(indxarr))

//POST YOUR DATA
this.httpClient.post('http://localhost/rajat/ajax/contact_query_submit/', data,httpOptions)
.subscribe(data => {
  console.log(data);
});

}

Your backend code will be

public function contact_query_submit(){

    if ($this->input->post()) {

        $postdata = file_get_contents("php://input");
        $_POST = json_decode($postdata,TRUE);
        $addArr = array(
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email'),
            'phone' => $this->input->post('phone'),
            'message' => $this->input->post('message'),
            'created' => time()
        );
        if($this->main_model->create('rjt_contact', $addArr)){
            $arr[] = array('type' => 'success', 'msg' => '<p>Your query has been received. <br>We will get back to you soon.</p>');
            echo json_encode($arr);
        }else{
           $arr[] = array('type' => 'warning', 'msg' => '<p>'.$this->db->last_query().'</p>');


            echo json_encode($arr);
        }
    }else{
        $arr[] = array('type' => 'warning', 'msg' => '<p>No data post yet</p>');
        echo json_encode($arr);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.