使用Ionic和AngularJS在$ scope中更改时,变量值不会在视图中更新

时间:2015-10-13 20:18:34

标签: javascript angularjs ionic-framework ionic

我使用Ionic 1.1和angularJS 1.4

进行以下简单应用

http://codepen.io/thurft/pen/zvzLqp

它会滚动ion-scroll中的项目列表,然后在highlight等于变量$index时尝试更改currentIndex课程。

当我输出console.log("currentIndex: " + $scope.currentIndex);时,我得到正确的值,但它在视图中永远不会改变。

我缺少什么,以便currentIndex变量在视图中正确更新? See working code

HTML

  <body ng-app="starter" ng-controller="AppCtrl">
    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content>
        <ion-scroll direction="y" on-scroll="gotScrolled()" delegate-handle="signsScroll">
          <div class="sign" ng-repeat="sign in signs" ng-class="{'highlight': $index === currentIndex}">{{sign}}</div>
        </ion-scroll>

      </ion-content>
    </ion-pane>
  </body>

JS

$scope.signs = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"];

      $scope.currentIndex = 0;


      $scope.gotScrolled = function () {

        var itemLength             = $scope.signs.length,
          containerHeight        = 100,
          viewingItemNumberObj   = {"min": itemLength + 1, "max":0};

        // Apply class depending whether they are visible within the container or not
        $.each($(".sign"), function () {
          if($(this).position().top < 0 || $(this).position().top > containerHeight -10) {
            $(this).addClass("notInView");
            $(this).removeClass("inView");
          } else {
            $(this).addClass("inView");
            $(this).removeClass("notInView");
          }
        });

        // Get min and max obj position thats showing in the scroller
        $.each($(".inView"), function () {
          var theIndex = $scope.signs.indexOf($(this).text());

          if(theIndex <= viewingItemNumberObj.min ) {
            viewingItemNumberObj.min = theIndex;
          } else if (theIndex >= viewingItemNumberObj.min && viewingItemNumberObj.max <= theIndex ) {
            viewingItemNumberObj.max = theIndex;
          }
        })

        // get the number and apply it to the currentIndex
        $scope.currentIndex = Math.floor((viewingItemNumberObj.min + viewingItemNumberObj.max) / 2);
        console.log("currentIndex: " + $scope.currentIndex);
      };

1 个答案:

答案 0 :(得分:2)

添加

$scope.$apply();

$scope.currentIndex = Math.floor((viewingItemNumberObj.min + viewingItemNumberObj.max) / 2);

它会起作用。

有关参考,请参阅http://codepen.io/anon/pen/VvzJqR