是否有可能在响应断点更新ng-repeat ?

Is it possible to update ng-repeat at responsive breakpoints?

本文关键字:更新 ng-repeat 断点 响应 有可能 是否      更新时间:2023-09-26

有可能让Angular在特定的屏幕尺寸下更新ng-repeat吗?

我有20个div,但是在640px及以下,我想只显示6个,在640px和1024px之间,我想显示15个,大于1024px,我想显示所有20个。

正如我提到的,我正在使用ng-repeat来推出div,我希望能够重新创建它??(不确定这是否是正确的术语,我正在学习)当浏览器达到这些大小之一时,ng-repeat函数。ng-repeat将被更新为需要滚出的项目数量,然后将它们滚出。

我是这样设置ng-repeat的:

.articles(ng-controller="articlesCtrl")
  .article(ng-repeat="article in articles | limitTo:15", class='item-{{ $index + 1 }}')

limitTo是一个angular过滤器,当你设置它的变量时,ng-repeat指令会重新编译它的内容(更多关于指令和$compile)

还可以设置一个函数:

ng-repeat="item in items | limitTo:calcLimit()"

,只返回你需要的

  $scope.calcLimit = function(limit) {
    if (resolution >= 1024)
      return 10;
    else if (resolution >= 640)
      return 6;
    else
      return 3;
  };

活塞的例子有乐趣!div =)

正如Sasxa所说,声明一个像"myScopeVar"或"someValue"这样的范围变量

JS -在你的控制器

$scope.numDisp = 6;
// based on screen width, but you can base on height as well http://www.w3schools.com/js/js_window_screen.asp
if(window.screen.width < 641)
    $scope.numDisp = 6; // 
else if(window.screen.width > 640 && window.screen.width < 1025)
    $scope.numDisp = 15
else if(window.screen.width > 1024)
    $scope.numDisp = 20
HTML:

.article(ng-repeat="article in articles | limitTo: numDisp", class='item-{{ $index + 1 }}')

更新

我看了看你的活塞,注意到你应该在指令中触发屏幕宽度检查。

var app = angular。模块("恰好",[]);

app.controller('MainCtrl', function($scope) {
  $scope.items = [
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  ];
  $scope.numDisp = 3;
});
app.directive('resizable', function($window) {
  return function($scope) {
    $scope.initializeWindowSize = function() {
      $scope.windowHeight = $window.innerHeight;
      // do width check here, especially since you have $window object here already
      if($window.innerWidth < 641)
          $scope.numDisp = 3; // 
      else if($window.innerWidth > 640 && $window.innerWidth < 1025)
          $scope.numDisp = 5;
      else if($window.innerWidth > 1024)
          $scope.numDisp = 10;
      console.log($window.innerWidth, $scope.numDisp); // check console for right output
      return $scope.windowWidth = $window.innerWidth;
    };
    $scope.initializeWindowSize();
    return angular.element($window).bind('resize', function() {
      $scope.initializeWindowSize();
      return $scope.$apply();
    });
  };
});