AngularJs ng-submit无法获得ng-model的值

时间:2015-09-09 10:39:11

标签: angularjs input angular-ngmodel ng-submit

我有 HTML

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

并在我的控制器

$scope.comment = "";

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

当我在input模型上进行更新时,它正常工作。但是当我按下回车时,我希望输入的值记录在控制台上。但它似乎无法从ng-model获得更新的值。

enter image description here

2 个答案:

答案 0 :(得分:2)

尝试将其作为参数传递:

<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);
}

答案 1 :(得分:1)

看起来一切正确看看。

&#13;
&#13;
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);
    }

  }
]);
&#13;
<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>
&#13;
&#13;
&#13;