检测 $last 的指令不适用于 angular.js 中的 ng-if

Wes*_*wai 5 javascript jquery directive angularjs angularjs-directive

我正在使用 angular.js 和 jquery 开发新闻提要页面。

我正在使用指令来检测要显示的最后一个提要。当它返回时scope.$last ==true,我调用一个函数来执行一些 Jquery 动画。

然后,我按日期将 ng-model 添加showYear到过滤器元素,并添加ng-if到过滤器元素。

我的问题是,当最后一个元素被过滤ng-if并且未呈现时,该指令无法检测scope.$last并运行feedPosition()

我尝试像下面的网址那样做,但它面临同样的问题:here

请帮忙。

这是我的代码:

HTML:

<div id="feedList">
    <div ng-repeat="feed in feeds | orderBy: '-date'" ng-if="show(feed.date)" feed-list-repeat-directive>
        //some content here
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript:

<script>
var feeds = [{
    "type" : "publications",
    "source" :"AAA",
    "date" : new Date(2014, 4, 10),
    "title" : "title 2014",
    "thrumb" : "thrumb1.jpg"
},{
    "type" : "tvc",
    "source" : "BBB",
    "date" : new Date(2015, 4, 10),
    "title" : "title 2015",
    "thrumb" : "thrumb2.jpg"
}];

var app = angular.module('anApp', []);
app.controller('anCtrl', function($scope) {
     $scope.showYear = 2015;
     $scope.feeds = feeds;
    $scope.show = function(yr){
        return Number(yr.getFullYear())==$scope.showYear;
    };
})
.directive('feedListRepeatDirective', function() {
  return function(scope, element, attrs) {
    if (scope.$last){
        feedPosition(true);
    };
  };
});


function feedPosition(){
    for(a=0; a<$('#feedList > div').length; a++){       
        // do something to animate elements position
    };
};
</script>
Run Code Online (Sandbox Code Playgroud)

she*_*lak 4

目前,$last适用于数组feeds,按 排序date。控制ng-if是否渲染每个项目,但它实际上并没有过滤列表。

为了以$last所需的方式过滤列表,请删除ng-if并使用 Angular 的过滤器。根据函数filter从数组中选择项目的子集,并将它们作为新数组返回。新数组仅包含函数返回的那些元素。feedsshowshowtrue

<div ng-repeat="feed in feeds | filter: show | orderBy: '-date'" feed-list-repeat-directive>
    //some content here
</div>
Run Code Online (Sandbox Code Playgroud)

请注意,show必须稍微修改该函数才能将完整的提要而不是日期作为输入:

$scope.show = function(feed){
    return Number(feed.yr.getFullYear())==$scope.showYear;
};
Run Code Online (Sandbox Code Playgroud)