简体   繁体   English

Angular View {{var}}正在更新,但是$ scope.var不会改变吗?

[英]Angular View {{ var }} updating, but $scope.var doesn't change?

I am using ui-bootstrap rating directive , and have encountered something weird. 我正在使用ui-bootstrap rating指令 ,并且遇到了一些奇怪的事情。

Below is the markup used for the directive. 以下是该指令使用的标记。 Two variables are passed into the directive, rateValue and rateMax 两个变量传递到指令中,rateValue和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. 奇怪的是,当我选择不同数量的星星时,我可以在视图中看到rateValue变量正在更新。 But the variable's value isnt updated in the $scope view model. 但是变量的值不会在$ scope视图模型中更新。

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

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM