我尝试使用来自api的数据更新dom,但是我得到了" $ watch未定义"这是我的ctrl
app.controller('counter', ['$scope', 'factory', function ($scope, factory) {
factory.get(function (res) {
$scope.proizvedeno = res;
$scope.output = $scope.proizvedeno.total_energy_output;
$scope.countTo = $scope.output;
$scope.countFrom = 0;
$scope.$watch("output", $scope.countTo)
console.log($watch);
$scope.reCount = function () {
$scope.countFrom = Math.ceil(Math.random() * 300);
$scope.countTo = Math.ceil(Math.random() * 7000) - Math.ceil(Math.random() * 600);
}; }]);
我尝试添加监视功能,自动更新dom,但这不起作用。有人可以帮我。
答案 0 :(得分:0)
让我把它作为答案,这样就会给问题带来更多app.controller('counter', ['$scope', 'factory', function ($scope, factory) {
factory.get(function (res) {
$scope.proizvedeno = res;
$scope.output = $scope.proizvedeno.total_energy_output;
$scope.countTo = $scope.output;
$scope.countFrom = 0;
$scope.$watch("output", $scope.countTo) //Changed this
console.log($watch); //removed this line
$scope.reCount = function () {
$scope.countFrom = Math.ceil(Math.random() * 300);
$scope.countTo = Math.ceil(Math.random() * 7000) - Math.ceil(Math.random() * 600);
}; }]);
。
您的实际代码:
app.controller('counter', ['$scope', 'factory', function ($scope, factory) {
factory.get(function (res) {
$scope.proizvedeno = res;
$scope.output = $scope.proizvedeno.total_energy_output;
$scope.countTo = $scope.output;
$scope.countFrom = 0;
$scope.$watch("output",
function handleChange( newValue, oldValue ) {
console.log( "$scope.output:", newValue );
})
$scope.reCount = function () {
$scope.countFrom = Math.ceil(Math.random() * 300);
$scope.countTo = Math.ceil(Math.random() * 7000) - Math.ceil(Math.random() * 600);
}; }]);
改革后的一个:
{{1}}
答案 1 :(得分:0)
大家好我用超时修复此问题,我不知道这是最好的解决方案,但这对我有用。 Thnx对所有人
app.controller('counter', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
$scope.reload = function () { //add new function for timer
$http.get(serviceBase + 'live-stats').
success(function (res) {
$scope.proizvedeno = res;
$scope.wireless_charging_count = $scope.proizvedeno.wireless_charging_count;
$scope.countTo3 = $scope.wireless_charging_count;
$scope.countFrom3 = 0;
$scope.reCount = function () {
$scope.countFrom3 = Math.ceil(Math.random() * 300);
$scope.countTo3 = Math.ceil(Math.random() * 7000) - Math.ceil(Math.random() * 600);
};
});
var reload = $timeout(function(){ //set here $timeout
$scope.reload();
}, 5000);
$scope.$on('$destroy', function(){ //must cancel $timeout
$timeout.cancel(reload);
});
};
$scope.reload();
}]);
U必须取消计时器,否则你会遇到类似我的问题:),在更改路由计时器仍在工作并从网址重新加载数据之后。 Thnx对每个人