Arak Tai'Roth
Arak Tai'Roth

Reputation: 408

Unable to submit data via form

I have a simple form:

<form ng-submit='addMessage()'>
    <input type='text' ng-model='chatMessage' placeholder='chat here' />
    <input type='submit' value='chat' />
</form>

And at the moment, a very simple function:

$scope.addMessage = function() {
    console.log($scope.chatMessage);
}

The console logging is just logging undefined, no matter what I type into the input box. Clearly I'm missing something, but I'm not sure what that is.

Upvotes: 0

Views: 236

Answers (3)

Azox
Azox

Reputation: 1940

This should work:

<form ng-submit='addMessage(chatMessage)'>
   <input type='text' ng-model='chatMessage' placeholder='chat here' />
   <input type='submit' value='chat' />
</form>

And in your controller:

$scope.addMessage = function(msg) {
    console.log(msg);
}

UPDATE

based on your comments i think you are looking for something like this:

        $scope.messages = [];

        $scope.$watch('messages', function(newMessage) {
            alert('hey, a message was added ! :' +newMessage);
        }, true);

        $scope.addMessage = function(msg) {
            $scope.messages.push(msg);
        };

Angular has so called watches, the watched function will trigger everytime when a new message is addded to the array. For more information about watches refer to the docs

Upvotes: 0

sylwester
sylwester

Reputation: 16498

Look for that fiddle maybe you missed something different .

<div ng-app="app">
    <div ng-controller="mainCtrl">
<form ng-submit='addMessage()'>
    <input type='text' ng-model='chatMessage' placeholder='chat here' />
    <input type='submit' value='chat' />
</form>
        <pre>{{msg | json}}</pre>
    </div>
</div>

JS:

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

app.controller("mainCtrl", function ($scope) {

    $scope.msg = [];

    $scope.addMessage = function () {

        $scope.msg.push($scope.chatMessage);
        console.log($scope.chatMessage);
        $scope.chatMessage = "";


    }

});

Upvotes: 0

Matt Way
Matt Way

Reputation: 33161

Depending on the way forms are used, sometimes $scope is out of context between the controller on the form. This is because addMessage(), and chatMessage are not on the same level of the $scope hierarchy.

One way to fix this is to create a container for your form items:

$scope.cont = {};
$scope.addMessage = function() {
    console.log($scope.cont.chatMessage);
}

And in the form:

<input type="text" ng-model="cont.chatMessage" placeholder="chat here"/>

This is also something you should definitely read if you are going to use angular more: http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html

Upvotes: 1

Related Questions