0

I am using ui-bootstrap rating directive, and have encountered something weird.

Below is the markup used for the directive. Two variables are passed into the directive, rateValue and rateMax

<div class="ratingContainer textCentered">
    <rating value="rateValue" max="rateMax"></rating>
</div>
<h4>
    {{rateValue}} / {{rateMax}}
</h4>

The weird thing is that i can see the rateValue variable being updated in the view, when i select different numbers of stars. But the variable's value isnt updated in the $scope view model.

app.controller( 'addModalCtrl', function($scope, $modalInstance, selectedMovie, myMovieService ) {

  $scope.rateValue = 0;
  $scope.rateMax = 10;
  $scope.selectedMovie = selectedMovie;

  $scope.addToLib = function( item ) {

    var jsonData = {
        tmdb_id: $scope.selectedMovie.id,
        my_rating: $scope.rateValue //this always remains 0
    };
Ivan Bacher
  • 5,855
  • 9
  • 36
  • 56
  • 1
    Could you perhaps be updating the value in a child scope? Try putting `rateValue` and `rateMax` into an object (like `rate.value` and `rate.max`) and put those in the view. If that fixes it, see [here](http://stackoverflow.com/a/14049482/2630455) why that is. – Steve Klösters Apr 22 '14 at 12:16

1 Answers1

3

Not sure exactly what goes wrong here, but I guess it's caused by the scope variables being primitives and not objects; which for technical reasons behaves unexpectedly.

In general it's better to use an object to store scope values instead of using variables directly. So you should put your scope variables in an object like this:

 $scope.vals = {};
 $scope.vals.rateValue = 0;
 $scope.vals.rateMax = 10;
 //etc.
 // Functions doesn't need to be in an object:
 $scope.addToLib = function( item ) { //...

and

 <h4>
     {{vals.rateValue}} / {{vals.rateMax}}
 </h4>
Community
  • 1
  • 1
Stein G. Strindhaug
  • 5,077
  • 2
  • 28
  • 41
  • 2
    It's not because "scope variables are being passed by value". It's because of prototypal inheritance. See [here](http://stackoverflow.com/a/14049482/2630455). – Steve Klösters Apr 22 '14 at 12:20
  • Fair enough, I've updated the answer. Though as a mental model I find thinking of the scope variables as being passed as parameters to a function, seems to works well. – Stein G. Strindhaug Apr 22 '14 at 12:28