0

I am trying simulate a review system. How does ng submit pass values over to the controller?

In my controller I have

$scope.reviews = function() {
  $scope.rating = 0;
  $scope.max = 5;
};
$scope.myTextArea = '';
$scope.saveReview = function(rating, myTextArea) {
  console.log(rating);
  console.log(myTextArea);
};

In my view, I have:

<form name="reviewForm" class="form-horizontal" ng-submit="saveReview(rating,    myTextArea)" novalidate>
  <div>
    <rating ng-model="rating" max="max" aria-labelledby="'product.title'"></rating>
  </div>
  <div>This is the rating: {{rating}}</div>
  <div class="animate-switch" ng-switch-when=true>
    <textarea ng-model="myTextArea" class="form-control" placeholder="Write a short review of the product." title="Review"></textarea>
  </div>
  <button type="submit" class="btn btn-primary pull-right">Submit Review</button>
</form>

When I submit the form, the saveReview function will be called and printout in the console is 0 and ''. So, none of the values are being saved/passed. Ng-model rating shows 5 stars and if you click on 4 stars, the {{rating}} will display 4.

Any ideas?

vincent l
  • 3
  • 1

1 Answers1

0

Don't pass anything into the saveReview() function on ng-submit. Instead let the saveReview() use the variables from scope. Also encapsulate the variables inside an object. For example: ng-model="review.rating" and ng-model="review.text". Assuming there are many, you need one to be an object anyway ;)

$scope.saveReview = function() {
  console.log($scope.review.rating);
  console.log($scope.review.text);
};
Vaelyr
  • 2,841
  • 2
  • 21
  • 34
  • hmm maybe I left out some information. I am using an ng-repeat that displays sections of: product.name selectable stars special reviewbox if 2 or less stars are selected So, if i encapsulate the variables, I begin to mess up the stars. The review code is this: $scope.reviews = function () { $scope.products = Products.query(); $scope.review.rating = 0; $scope.max = 5; }; I call this review function at the start of the page render. – vincent l Mar 18 '16 at 20:40
  • Encapsulating makes it easier to pass the data around for any other operations, it shouldn't affect anything. I am assuming the submit operates just on one entry at the time. So if you are looping over the entries, then it makes even more sense. Just let the save function take no arguments and use variables from scope. Else I need more information what the actual problem is. – Vaelyr Mar 18 '16 at 20:52
  • Thanks for the input and quick replies. Ill work on it some more. I am very new to angular. I would greatly appreciate any resources you care to recommend. – vincent l Mar 18 '16 at 21:20
  • There are tons of tutorials and examples, I recommend watching tutorials in video formats from https://egghead.io/ for example, they have great free videos that should teach you a lot. – Vaelyr Mar 18 '16 at 21:31