我有以下使用 Ionic 1.1 和 angularJS 1.4 的简单应用程序
http://codepen.io/thurft/pen/zvzLqp
它会滚动 ion-scroll
中的项目列表,然后在 $index
等于时尝试更改 highlight
类变量currentIndex
。
当我输出 console.log("currentIndex: "+ $scope.currentIndex);
时,我得到了正确的值,但它在 View 中永远不会改变。
为了使 currentIndex
变量在 View 中正确更新,我缺少什么? 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);
};
最佳答案
添加
$scope.$apply();
之后
$scope.currentIndex = Math.floor((viewingItemNumberObj.min + viewingItemNumberObj.max) / 2);
它会起作用。
关于javascript - 使用 Ionic 和 AngularJS 在 $scope 中更改变量值时, View 中的变量值未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33111866/