2

I have this HTML :

<form ng-submit="addComment()">
    <md-input-container flex>
        <label>Shoutout</label>
        <input type="text" ng-model="comment">
    </md-input-container>
</form>

and in my Controller :

$scope.comment = "";

$scope.addComment = function(){
    console.log("Value from input", $scope.comment);
    $scope.comment = "test"
    console.log("New Value", $scope.comment);
}

It works fine when im typing on the input the model is updating and all. But when I press enter I expect the value from the input to be logged on the console. But it seems that it cannot get the updated value from the ng-model.

enter image description here

2 Answers 2

3

Try passing it as an argument:

<form ng-submit="addComment(comment)">
  <md-input-container flex>
    <label>Shoutout</label>
    <input type="text" ng-model="comment">
  </md-input-container>
</form>

$scope.addComment = function(comment){
  console.log("Value from input", comment);
  $scope.comment = "test";
  console.log("New Value", comment);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Nice thanks. 1 question though. How do I make the input empty again?
@GreenFox Just do comment = "";
Im doing $scope.comment = "" inside the addComment() but it does not work. :(
What if you set it to null?
It seems that the problem is occuring due to the DOM is loaded before the Javascript because Im populating the views via ng-repeat based on the response from http. I solved it by putting a dynamic id on the input and used jquery to empty the input like $('#comment_'+someid).val('');
1

It seems all correct have a look.

angular.module('app', []).controller('MyController', ['$scope',
  function($scope) {

    $scope.comment = "";

    $scope.addComment = function() {
      console.log("Value from input", $scope.comment);
      $scope.comment = "test"
      console.log("New Value", $scope.comment);
    }

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyController">
  <form ng-submit="addComment()">
    <md-input-container flex>
      <label>Shoutout</label>
      <input type="text" ng-model="comment">
    </md-input-container>
  </form>
  
  <p>{{"log-->> "+comment}}</p>
<div>

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.