SARAN SARAN - 21 days ago 5
AngularJS Question

Angular Js Textarea Value not assigned through ng-model

I'm new to this angular JS. I have one different issue.
Please anyone help.
I have this code in html:

<textarea ng-model="user_comments" md-maxlength="500" rows="5" required></textarea>
<input type="text" ng-model="text_comment">
<button ng-click="add_cmnt(text_comment,user_comments)">Added into textarea</button>


and Controller code is this:

$scope.add_cmnt = function(data1, data2){
$scope.user_comments = data1+data2;
console.log($scope.user_comments);
}


When i click this added into textarea button the text-comment was append into user_comments. But it's not work. I don't know why? Please anyone help.

Answer

You can directly use the model values without sending any parameters form the function.

Also covert to string before appending.

$scope.user_comments.toString() + $scope.text_comment.toString()

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.add_cmnt = function(){
$scope.text_comment = $scope.text_comment ? $scope.text_comment : ''
$scope.user_comments = $scope.user_comments ? $scope.user_comments : ''
  $scope.user_comments = $scope.user_comments.toString() + ' ' + $scope.text_comment.toString()
$scope.text_comment = "";
  console.log($scope.user_comments);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<textarea  ng-model="user_comments" md-maxlength="500" rows="5" required></textarea>
<input type="text" ng-model="text_comment">
<button ng-click="add_cmnt()">Added into textarea</button>

</div>


</body>
</html>

Please run this snippet

Here is the fiddle link

Comments