首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >angular-meteor:如何从`helpers`方法中$watch集合?

angular-meteor:如何从`helpers`方法中$watch集合?
EN

Stack Overflow用户
提问于 2016-03-08 20:08:22
回答 2查看 257关注 0票数 1

我在由helper函数设置的上下文变量的指令中使用了ng-repeat,但该指令并没有呈现整个集合。据我所知,它正在呈现它在指令postLink时找到的任何内容,但当集合增长时不会重新呈现。

我试图将$watch添加到指令中,但它只在加载时触发一次,即使随着Collection的增长也是如此。

下面是我从meteor-angular-socially教程中创建的示例,请参阅:https://github.com/Urigo/meteor-angular-socially/tree/step_14

文件:client/parties/parties-list/parties-list.component.js

代码语言:javascript
复制
angular.module('socially').directive('partiesList', function () {
  return {
    restrict: 'E',
    templateUrl: 'client/parties/parties-list/parties-list.html',
    controllerAs: 'partiesList',
    controller: function ($scope, $reactive) {
      $reactive(this).attach($scope);

      window.vm = vm = this;
      $scope.$watch(vm.parties, function(newV, oldV) {
        // this $watch fires once when the controller is loaded, but never again
        // but vm.parties is updated when new parties are added
        return console.warn('vm.parties.count=' + (newV != null ? newV.length : void 0));
      });

      ...

      this.helpers({
        parties: () => {
          return Parties.find({}, { sort : this.getReactively('sort') });
        },
        users: () => {
          return Meteor.users.find({});
        },
        partiesCount: () => {
          return Counts.get('numberOfParties');
        }
      });

更新集合时不会触发$scope.$watch。我在这里做错了什么?

EN

回答 2

Stack Overflow用户

发布于 2016-03-08 21:58:08

多哈!答案是使用scope.$watchCollection而不是scope.$watch

票数 0
EN

Stack Overflow用户

发布于 2016-03-09 19:47:37

@michael scope.$watchCollection在某些情况下可能会起作用,但如果您想要监视所有数据更改,则需要使用deep watch:$scope.$watch(func,true)

代码语言:javascript
复制
$scope.$watch(vm.parties, function(newV, oldV) {
    return console.warn('vm.parties.count=' + (newV != null ? newV.length : void 0));
}, true);

此外,如果将第二个参数设置为true,getReactively也可以使用深度监视:$scope.getReactively('var', true)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35866993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档