javascript - $watch 没有在函数之外更新数组?

标签 javascript arrays angularjs scope watch

我查看了许多 StackOverflow 文章,试图找出为什么我的 $watch 不起作用,其中大多数都引用了这样一个事实:要么人们没有更新对象,要么第三个参数,即对象相等运算符未按照此处这些文章中的指定设置为 true:

$watch not firing on data change

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

这是我的代码:

Controller :

$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 数组是空的。我尝试在 returnfriend 语句之后添加 $scope.$apply 函数,但我收到一个问题,说 digestcycle 是仍在进行中。我在第三个参数中添加了据我所知,应该执行从我的 currentUser.friends 数组到我的 selectionPending 数组的复制。我不太清楚为什么,有人可以帮助我吗?谢谢!

最佳答案

尝试使用 $watchCollection 而不是 $watch 希望可以工作

关于javascript - $watch 没有在函数之外更新数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25573293/

相关文章:

javascript - Pixi.js 从动画 gif 文件生成 SpriteSheet 动画或 MovieClip

javascript - 在Jquery中,如何延迟执行由异步调用组成的同步函数?

sql - VB.NET 声明错误

arrays - 在 matlab 中计算 3 维元胞数组的均值

angularjs - 多方向angularjs View 动画

javascript - 在 Bootstrap 可折叠侧边栏导航中添加 Cookie

javascript - 是否有一些代码可用于定位元素及其父对象的偏移量和文本索引?

javascript - TypeScript 错误 TS 2094/2095 属性 'x' 在类型 'JQuery' 的值上不存在

c++ - 制作结构数组?

AngularJS:服务、提供商、工厂