AngularJS ng-repeat过滤器:{visible:true}不遵循属性更改

时间:2014-07-15 18:42:31

标签: javascript angularjs angularjs-ng-repeat

http://scythargon.github.io/

http://scythargon.github.io/main.js

var myApp = angular.module('myApp', ['infinite-scroll']);

myApp.controller('DemoController', function($scope, $timeout, $rootElement) {
    $scope.$rootElement = $rootElement;
    $scope.$timeout= $timeout;

    $scope.init = function(){
        $scope.posts = [
            {id: 1},
            {id: 2},
            {id: 3},
            {id: 4},
            {id: 5},
            {id: 6},
            {id: 7},
            {id: 8},
        ];

        window.posts = $scope.posts;
        _.each($scope.posts, function(post){
            post.visible = true;
        });
        //$scope.posts[1].visible = false;
    };

    $scope.is_visible = function(item) {
      return item.visible;
    };

    $scope.hide_topmost_items = function(){
        _.each($scope.posts, function(post){
            var elem = $('#post_' + post.id);
            if (elem.position().top + elem.height() + 500 < window.pageYOffset){
                post.visible = false;
                window.scrollTo(0, window.pageYOffset - elem.height());
                //elem.hide();
                console.log('#post_' + post.id + ' is hidden now')
            }
        });
    };

    $(window).on('scroll', $scope.hide_topmost_items);

    $scope.loadMore = function() {
        var length = $scope.posts.length;
        var last = $scope.posts[length - 1];
        for(var i = 1; i <= 8; i++) {
            $scope.posts.push({id: i + length});
        }
    };

    $scope.init();
});

https://github.com/scythargon/scythargon.github.io

我希望它隐藏比当前用户窗口高得多的元素,它通过jquery(注释掉elem.hide();行)但不是以角度方式工作,甚至试图在互联网上使过滤功能尽可能多的帖子建议,但结果相同 - 它在init(注释掉visible: false行)上捕获$scope.posts[1].visible = false;但在动态更改时却没有。

1 个答案:

答案 0 :(得分:1)

您的$scope.hide_topmost_items()是从外角($(window).on('scroll'))调用的,因此您必须在更改$ scope中的任何属性后手动调用$scope.$apply()

$scope.hide_topmost_items = function(){
  _.each($scope.posts, function(post){
    var elem = $('#post_' + post.id);
    if (elem.position().top + elem.height() + 500 < window.pageYOffset){
      post.visible = false;
      window.scrollTo(0, window.pageYOffset - elem.height());
      //elem.hide();
      console.log('#post_' + post.id + ' is hidden now')
    }
  });

  $scope.$apply(); // this is required when called from outside angular
};

希望得到这个帮助。