-1

I am trying to change top position of a DIV on Scroll event -

In controller i have-

    angular.element($window).on("scroll", function(e) {
        vm.scrollTop = angular.element($window).scrollTop()+'px';
        console.log(vm.scrollTop);
    }); 

In html -

<div ng-style="{'top': vm.scrollTop}">
    Hello World
</div>

On scroll event is printing scrollTop values in console but "Div" style never gets updated.

Please correct me if this is syntactically incorrect.

NewBee
  • 839
  • 7
  • 18
  • 42
  • `ng-style` take an `expression` not a `value`, try this `
    `
    – Ayoub Nov 16 '17 at 23:09
  • I updated my question for the same but run time expression are not updating style of the div (top -> calculated scroll) – NewBee Nov 16 '17 at 23:16
  • Close your attribute with a double quote. – Jim Cote Nov 16 '17 at 23:22
  • 1
    You also need to call `$scope.$apply();` after setting `vm.scrollTop` because the event handler is executing outside of angular's awareness. – Jim Cote Nov 16 '17 at 23:24
  • Well, $scope.$apply does that. Thanks Jim. You mind providing above comment as answer, i will mark it as the answer for others – NewBee Nov 16 '17 at 23:35

2 Answers2

1

You need to call $scope.$apply(); after setting vm.scrollTop because the event handler is executing outside of angular's awareness.

Jim Cote
  • 1,746
  • 3
  • 15
  • 26
1

You can use $scope.$apply or $scope.$watch.

Here's snippet using $scope.$apply.

function TodoCtrl($scope, $document, $window) {
   $scope.scrollTop = 30;
     $document.bind('scroll', function(){
        $scope.$apply(function(){
   $scope.scrollTop = $window.scrollY;
      });
   });
   $scope.getStyle = function(){
        var styles = {}
        styles['margin-top'] = $scope.scrollTop + 'px';
        return styles;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<div ng-app>
  <h2>Top</h2>
  <div ng-controller="TodoCtrl">
     <div ng-style="getStyle()">
         Hello World
     </div>
  </div>
 <div style="height: 1000px; border: solid 2px red;"></div>
</div>
artgb
  • 3,177
  • 6
  • 19
  • 36