-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.

5
  • ng-style take an expression not a value, try this <div ng-style="{'top': vm.scrollTop}"> Commented Nov 16, 2017 at 23:09
  • I updated my question for the same but run time expression are not updating style of the div (top -> calculated scroll) Commented Nov 16, 2017 at 23:16
  • Close your attribute with a double quote. Commented Nov 16, 2017 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. Commented Nov 16, 2017 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 Commented Nov 16, 2017 at 23:35

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.