我正在尝试使用Angularjs创建一个计数器,该计数器应该计入该分区中已存在的数字。这是我的html片段。
<div class="circle-home">
<span class="circle-home-score " id="counterofreviews" data-count="{{noReviews}}">{{noReviews}}</span> REVIEWS
</div>
现在,当我尝试在范围内获取值时,我将其视为{{noReviews}}而不是其值。
这是我的AngularJs代码。
var demoApp = angular.module(['demoApp','ngRoute','ui.bootstrap']);
demoApp.controller('SearchController',function ($scope, $http, $facebook, $interval){
$scope.noReviews=100;
$scope.childOnLoad = function() {
$scope.uppercount=$("#counterofreviews").text();
$scope.no_Reviews=0;
console.log($scope.uppercount);
var stop;
stop = $interval(function() {
if ($scope.uppercount >$scope.no_Reviews) {
$scope.noReviews=$scope.no_Reviews;
$scope.no_Reviews++;
console.log('Inside if statement');
} else {
$scope.stopFight();
}
}, 100);
};
$scope.stopFight = function() {
if (angular.isDefined(stop)) {
$interval.cancel(stop);
stop = undefined;
}
};
$scope.childOnLoad();
};
console.log($ scope.uppercount)的输出为{{noReviews}}。我无法找到适当的方法来做到这一点。请建议更正或任何其他更好的方法相同的perpose。
答案 0 :(得分:1)
不确定为什么使用jQuery获取#counterofreviews
值。值是否因为它是从服务器端脚本中添加的?
正如评论中所提到的,您的代码可能无法正常工作,因为jQuery.text()
正在返回一个字符串。使用parseInt(text)
可以正常工作。
请查看下面的演示,并点击此处jsfiddle。
它更具角度,应该可以帮助您开始使用计数器。
var demoApp = angular.module('demoApp', []); //'ngRoute','ui.bootstrap']);
demoApp.controller('SearchController', function ($scope, $http, $interval) { //$facebook,
$scope.noReviews = 100;
//$scope.childOnLoad = function () {
this.upperCount = 10; //$("#counterofreviews").text();
console.log(this.upperCount);
var stop;
this.startCounter = function () { // needed for re-run on change
//console.log(stop, this);
this.no_Reviews = 0;
if ( angular.isUndefined(stop) )
stop = $interval(checkCount.bind(this), 100);
};
this.startCounter();
//};
function checkCount() {
if (this.upperCount >= this.no_Reviews) {
this.noReviews = this.no_Reviews;
this.no_Reviews++;
//console.log('Inside if statement');
} else {
stopFight();
}
}
function stopFight() {
if (angular.isDefined(stop)) {
$interval.cancel(stop);
stop = undefined;
}
};
//$scope.childOnLoad();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" class="circle-home" ng-controller="SearchController as ctrl">Review max.:
<input ng-model="ctrl.upperCount" ng-change="ctrl.startCounter()"/> <span class="circle-home-score " id="counterofreviews" data-count="{{ctrl.upperCount}}">{{ctrl.noReviews}}</span> REVIEWS</div>
&#13;