我使用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);
};
答案 0 :(得分:2)
添加
$scope.$apply();
后
$scope.currentIndex = Math.floor((viewingItemNumberObj.min + viewingItemNumberObj.max) / 2);
它会起作用。