【问题标题】:$watch not updating array outside of function?$watch 不在函数之外更新数组?
【发布时间】:2014-10-23 18:16:42
【问题描述】:

我查看了许多 StackOverflow 文章,试图找出我的 $watch 不起作用的原因,其中大多数都引用了这样一个事实,即人们没有更新对象,或者第三个参数,对象相等运算符未设置为 true,如这些文章中所述:

$watch not firing on data change

$watch is not working when model is updated in scope.$apply in directive

这是我的代码:

控制器:

$scope.selectionPending = [];

// helper method to get selected friends
$scope.selectedFriends = function() {
  return filterFilter($scope.currentUser.friends, { requested: true });
};

// watch friends for changes
$scope.$watch('currentUser.friends|filter:{requested:false}', function (nv, ov) {
  console.log("Nv: ", nv);
  if(nv){
    console.log("$scope.selectPending: ", $scope.selectionPending);
    $scope.selectionPending = nv.map(function (friend) {
      return friend;
          //This is just an example of what my friend object may look like:
          /* Example Friend Object just to show what is inside this object
             {
             'requested': false,
             'pending': true,
             'username': "Test"
              }; */
    });
  }
}, true);

$scope.addPendingFriend = function(){
  console.log("SelectionPending: ", $scope.selectionPending);
  //Problem: Nothing is printing out: my selectionPending array is empty.
  ...
}

HTML 文件:

  <label ng-repeat="friend in currentUser.friends" ng-if="friend.pending == true">
    <input
      type="checkbox"
      name="selectedFriends[]"
      value="{{friend.requested}}"
      ng-model="friend.requested"
    > {{friend.username}}
  </label>
    <div>
      <button type = "button" class="btn btn-primary" ng-click="addPendingFriend()" ng-class="{'btn-default': friend.friendsToAdd, 'disabled': !friend.friendsToAdd}">
        {{friend.friendAddText}}
      </button>
    </div>

基本上,我的 UI 中有一些复选框,我用 ng-repeat 显示,当我选择一个复选框时,我将该对象存储到 $scope.selectPending 数组中。这很好用,但是当我尝试使用我的函数$scope.addPendingFriend() 实际访问任何变量时,我的$scope.selectPending 数组是空的。我试图在return friend 语句之后添加$scope.$apply 函数,但我收到一个问题,说digest cycle 仍在进行中。我添加了第三个参数,据我所知,它应该从我的currentUser.friends 数组复制到我的selectionPending 数组。我不太清楚为什么,有人可以帮助我吗?谢谢!

【问题讨论】:

    标签: javascript arrays angularjs scope watch


    【解决方案1】:

    尝试使用 $watchCollection 而不是 $watch 希望这样会起作用

    【讨论】:

    • 你在使用 $watchCollection 时删除了第三个参数 true 吗?
    • 是的,但我仍然遇到同样的问题。
    猜你喜欢
    • 2016-08-05
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多