简体   繁体   中英

ScrollHeight not changing when ng-repeat is updated

I've provided a Plunker below, when you click the button a loop is performed that adds data to an ng-repeat. After each loop the data is supposed to console.log() the ScrollHeight of the container. I would assume that it would log three unique number, but instead it logs the final height of the div three times. Any thoughts?

http://plnkr.co/edit/dMbrWsrwfQuf0HCv8Ggn?p=preview

CONTROLLER:

$scope.shares = [{
  name: 'all'
}, {
  name: 'day'
}, {
  name: 'I'
}, {
  name: 'dream'
}, {
  name: 'about'
}, {
  name: 'javascript'
}, ]

$scope.heights = [];
$scope.dataset = [];

var tableview = document.getElementById('tableview');

var TableViewOne = new TableView($scope.shares);


$scope.testing = function() {

  for (var i = 0; i < 3; i++) {
    TableViewOne.setData();
    TableViewOne.setHeight();
  }

}

function TableView(data) {

  var heights = [];

  this.setData = function() {
    var temp = data;
    for (var i = 0, len = temp.length; i < len; i++) {
      $scope.dataset.push(temp[i]);
    }
  }

  this.setHeight = function() {
    angular.element(document).ready(function() {
      heights.push(tableview.scrollHeight);
      console.log(heights);
    });
  }

}

Give width, height and overflow CSS to "ul" tag in style.css

Style.css:

    width:400px;
    height:300px;
    overflow:overlay;

Updated plunker : http://plnkr.co/edit/2dyER88Hkx1RNGGZ5iSG?p=preview

When you update the model, angular does not update its view immediately inside the same function. Angular updates the view at the end of the current cycle within its digest loop. That's why you don't see the updated height immediately.

When working with MVC architecture like angular, you should not access the view (DOM) directly in your controller's code. Try to restructure your code to only modify the model and let angular handle the DOM manipulation for you.

If you need to handle scroll event to add more items, you could try this:

$("#tableview").scroll(function(){
    $scope.$apply(function(){ //let angular aware of changes from events outside of angular.

       //do your logic to add more items.
    });
});

Another way to wrap this logic to make it integrated nicely with angular is to write a custom directive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM