changing a controller scope variable in a directive is not reflected in controller function

前端 未结 4 493
傲寒
傲寒 2020-12-16 08:11

In my directive, I have a controller variable, page which gets incremented when you press the button in the directive. However, the next line, scope.alertPage()

4条回答
  •  难免孤独
    2020-12-16 09:02

    The problem is that the timeline is off.

    1. button clicked, incrementPage()
    2. directive scope value incremented (now 2)
    3. alertPage() parent scope value read (still 1)
    4. parent scope updated as part of digest (now 2)

    To get around this, you need to either call the alert function after the digest cycle (e.g. $timeout) or you need to watch for changes in the parent scope.

    // in controller
    $scope.$watch('page', function (currentValue, previousValue) {
      // initially triggered with same value
      if (currentValue > previousValue) {
        alert(currentValue)
      }
    })
    

    Then change the value naturally.

    // in directive html
    

提交回复
热议问题