AngularJS:基本 $watch 不起作用 [英] AngularJS : Basic $watch not working

查看:39
本文介绍了AngularJS:基本 $watch 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 AngularJS 中设置手表,但显然我做错了什么,但我无法弄清楚.手表在立即加载页面时触发,但是当我更改监视值时,它不会触发.作为记录,我还在匿名函数上设置了 watch 以返回被监视的变量,但我得到了完全相同的结果.

我在下面搭建了一个最小的例子,在控制器中做所有事情.如果它有所不同,我的实际代码已连接到指令中,但两者都以相同的方式失败.我觉得一定有一些基本的东西我错过了,但我只是没有看到.

HTML:

<div ng-controller="testCtrl">

JS:

var app = angular.module('testApp', []);功能 testCtrl($scope) {$scope.hello = 0;var t = setTimeout( function() {$scope.hello++;console.log($scope.hello);}, 5000);$scope.$watch('hello', function() { console.log('watch!'); });}

超时有效,hello 递增,但手表没有触发.

演示在 http://jsfiddle.net/pvYSu/

解决方案

这是因为你在 Angular 不知道的情况下更新了值.

你应该使用 $timeout 服务而不是 setTimeout,你就不用担心这个问题了.

function testCtrl($scope, $timeout) {$scope.hello = 0;var t = $timeout( function() {$scope.hello++;console.log($scope.hello);}, 5000);$scope.$watch('hello', function() { console.log('watch!'); });}

或者你可以调用 $scope.$apply();强制角度重新检查值并在必要时调用手表.

var t = setTimeout( function() {$scope.hello++;console.log($scope.hello);$scope.$apply();}, 5000);

I'm attempting to set up a watch in AngularJS and I'm clearly doing something wrong, but I can't quite figure it out. The watch is firing on the immediate page load, but when I change the watched value it's not firing. For the record, I've also set up the watch on an anonymous function to return the watched variable, but I have the exact same results.

I've rigged up a minimal example below, doing everything in the controller. If it makes a difference, my actual code is hooked up in directives, but both are failing in the same way. I feel like there's got to be something basic I'm missing, but I just don't see it.

HTML:

<div ng-app="testApp">
    <div ng-controller="testCtrl">
    </div>
</div>

JS:

var app = angular.module('testApp', []);

function testCtrl($scope) {
    $scope.hello = 0;

    var t = setTimeout( function() { 
        $scope.hello++;
        console.log($scope.hello); 
    }, 5000);

    $scope.$watch('hello', function() { console.log('watch!'); });
}

The timeout works, hello increments, but the watch doesn't fire.

Demo at http://jsfiddle.net/pvYSu/

解决方案

It's because you update the value without Angular knowing.

You should use the $timeout service instead of setTimeout, and you won't need to worry about that problem.

function testCtrl($scope, $timeout) {
    $scope.hello = 0;

    var t = $timeout( function() { 
        $scope.hello++;
        console.log($scope.hello); 
    }, 5000);

    $scope.$watch('hello', function() { console.log('watch!'); });
}

Or you could call $scope.$apply(); to force angular to recheck the values and call watches if necessary.

var t = setTimeout( function() { 
    $scope.hello++;
    console.log($scope.hello); 
    $scope.$apply();
}, 5000);

这篇关于AngularJS:基本 $watch 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆