在 controller/directive 中观看流星 collection

Watch meteor collection in controller/directive

这个问题主要是关于 angular-meteor 包 AngularJs 1.x

我正在尝试观察流星 collection 并在它发生变化时进行一些计算。

angular.module('my-app').controller('MyCtrl', ['$scope', '$meteor', function($scope, $meteor) {
    var filter = {myfield: 10};
    $meteor.subscribe('mycollection', filter);
    $scope.mycollection = $scope.$meteorCollection(Mycollection);

    $scope.$watch('mycollection', function () {
        console.log($scope.mycollection.length)
    });
}]);

但是没用。 watch函数只会在$scope.mycollection为空时被调用一次,无论mycollection改变了多少次。如何观察mycollection的变化?

您需要将 object Equality 选项设置为 true 才能设置 deep watcher

$scope.$watch('mycollection', function (newVal) {
    console.log($scope.mycollection.length)
}, true); //true for deep watch

如果你不想使用 deep watcher,你可以使用 shallow watcher $watchCollection,因为 deep watcher 会影响你是否正在使用 deep watcher。