【问题标题】:$scope.watch ('$scope',.. in Angular$scope.watch ('$scope',.. 在 Angular 中
【发布时间】:2016-03-21 01:12:38
【问题描述】:

我想检查范围内的每一个变化是否有趣,我尝试了以下方法:

$scope.$watch('$scope', function(newValue) {
    console.log ("$scope's NewValue", newValue);
}, true);

我收到日志消息:

$scope's NewValue undefined

那,我正在尝试的,是可能的吗?

【问题讨论】:

    标签: angularjs scope watch


    【解决方案1】:

    我真的建议你不要这样做。这将在您的应用程序中产生很高的成本。

    $scope.$watch(function() { // First function must return the object that you want to watch.
        return $scope;      
    },
    function(newValue, oldValue) { // This is a callback executed everytime your $scope will change
        console.log("$scope's NewValue : ", newValue);   // You should rather use $log if you want to unit test your code one day
    },
    true   // Needed to tell angular to watch deeply inside $scope (every sub item).
    );
    

    【讨论】:

    • 难以置信,Angular 在后台做了什么!谢谢,它的工作延迟很大,而且有一些错误:Error: [ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported.
    • @Vienna 这里没有什么神奇之处。每当 Angular 检测到有变化时,他都会触发你应用的所有手表。因此,请谨慎使用 $watch,或者避免使用它
    猜你喜欢
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多