循环闭包内的Angular $ watch未按预期工作

时间:2016-03-10 07:44:14

标签: javascript angularjs loops closures watch

我正在尝试在循环中动态添加观察者。首先,我正在观察display_groups数组的长度何时发生变化,何时发生变化,我想确保每个显示组都有current_page属性上的监视(这是用于分页)。 / p>

我在watchDelegate的循环中添加了一个闭包,它返回关联显示组的当前页面属性。这实际上一切正常,我的问题是我需要访问同一display_group的另一个属性来执行分页逻辑,我找不到访问正确显示组的方法。我在下面添加了另一个函数displayGroupDelegate,但它总是返回最后一个循环的显示组。

我对angular(和JS闭包)相当新,所以任何建议都值得赞赏。感谢。

    display_group_watchers = []
    #watch for when display groups are added/removed
    $scope.$watch 'display_groups.length', ((newValue, oldValue) ->
      if newValue and (newValue != oldValue)
        for watcher in display_group_watchers
          watcher() #this clears out existing watchers
        display_group_watchers = [] #reset the array

        #set up a watch for the current page of each display group
        for key, display_group of $scope.display_groups
          watchDelegate = ((j) ->
            ->
              $scope.display_groups[j].current_page
          )(key)

          displayGroupDelegate = ((j) ->
            ->
              $scope.display_groups[j]
          )(key)

          watcher = $scope.$watch watchDelegate, ((newValue, oldValue) ->
            #only fire the change if navigating to a page i.e. going from undefined to 1 is just the inital load of data
            if newValue and (newValue != oldValue) and not (newValue ==1 and oldValue == undefined)
              ########this always returns the last display_group, not the one from the current loop!!!!
              console.log "user_tasks_to_expand_sym: #{displayGroupDelegate().user_tasks_to_expand_sym}"
          ), true
          display_group_watchers.push(watcher)
    ), true

0 个答案:

没有答案