0

How to add value to ng-model in angularjs. my html is:

<textarea rows="5" ng-model="comment.comment_text"></textarea>
<input type="hidden" ng-model="comment.task_id" value="{{task.id}}">
<input type="hidden" ng-model="comment.user_id" value="{{profile.id}}">
<button type="submit" class="btn btn-success" ng-click="create(comment)">Send</button>

and angular controller:

$scope.create = function(comment) {
     console.log(comment);
};

when click on button show result in console:

{comment_text: "test"}

BUT I want to show like this:

{comment_text: "test", user_id:1 ,task_id:53}
1
  • No, I want to set default value for comment.user_id Commented Mar 17, 2016 at 7:19

2 Answers 2

2

On your controller's constructor you should definitely instantiate the initial value of your 'comment' variable using:

$scope.comment = $scope.comment || {
     user_id: 'amcpanaligan',
     comment_text: 'sample'
     //// other object property declaration goes here...
};
Sign up to request clarification or add additional context in comments.

4 Comments

I think add ng-init="comment.task_id = task.id" to html is better than, but because task.id load after multi second it's doesn't work. Do you have any suggestion?
Why does loading task.id takes multi second? Where do you get it? If you are using a promise consider using the 'then' block of your promise.
Yes I use promise, I fetch task.id from database and I should wait for multi millisecond
So you are using some service or something that uses angular's $http or $resource service. You can initially set the values of some variables in your constructor and do something like $scope.comment.task_id = task.id on your promise's 'then' block
1

value={{someValue}} does not make sense. You should use only ng-model for text input hidden

function Ctrl($scope) {
  $scope.task = {
    id: 1
  }
  $scope.create = function(comment) {
    comment.taskId = $scope.task.id;
    console.log(comment);

  };
}


<div ng-app="">
  <div ng-controller="Ctrl">
    <textarea rows="5" ng-model="comment.comment_text"></textarea>
    <input type="hidden" ng-model="task.id">
    <button type="submit" class="btn btn-success" ng-click="create(comment)">Send</button>
  </div>
</div>

see fiddle

2 Comments

I want to add default value to comment.user_id in html
Thanks, I think add ng-init="comment.task_id = task.id" to html is better than, but because task.id load after multi second it's doesn't work. Do you have any suggestion?

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.