-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}">
    – Ayoub
    CommentedNov 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)
    – NewBee
    CommentedNov 16, 2017 at 23:16
  • Close your attribute with a double quote.
    – Jim Cote
    CommentedNov 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.
    – Jim Cote
    CommentedNov 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
    – NewBee
    CommentedNov 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.

    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>

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.