下面我有代码示例,它将根据ng-repeat的模型属性成功分组数据,但仅限于初始页面加载。所以例如在负载上我做
$scope.filter_items.group_1 = 'propb';
,正确地重复并按propb分组。如果我将其切换为propa
,则相同。
问题是页面加载后,通过输入更改filter_items
模型对于不更新的重复重复没有影响。我尝试使用。$ apply()方法,但没有任何工作(从我读到的,我不应该使用它)。如何在模型输入更改后重新绘制ng-repeat?
注意:我使用memoize函数来避免Angular摘要错误,没有它就会发生错误。
<!DOCTYPE html>
<html>
<head>
<script src="//code.angularjs.org/1.3.0/angular.js" data-semver="1.3.0" data-require="angular.js@*"></script>
<script data-require="underscore.js@*" data-semver="1.6.0" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script>
var app = angular.module("MyApp", []);
app.controller('MyCtrl', function($scope) {
$scope.filter_items = {};
$scope.filter_items.group_1 = 'propb';
$scope.items = [{id:"1", propa:"one", propb:"uno"},{id:"2", propa:"one", propb:"tres"}]
return
});
app.filter('myFilter', function() {
return _.memoize(function(items, filter_items) {
return _.groupBy(items, filter_items.group_1);
}
);
});
</script>
</head>
<body ng-app="MyApp">
<div ng-controller="MyCtrl">
Group by<br>
<select ng-model="filter_items.group_1">
<option value="propa">A</option>
<option value="propb">B</option>
</select>
<div ng-repeat="(group1, g_items) in items| myFilter:filter_items">
<h2>{{group1}}</h2>
</div>
</div>
</body>
</html>
答案 0 :(得分:0)
我无法让您的代码正常工作,或者只是我不理解或错过的东西。但是,如果自定义过滤器给您带来了麻烦,为什么不在控制器中放入简单的分组功能呢?
说,你的控制器
var app = angular.module("MyApp", []);
app.controller('MyCtrl', function($scope) {
$scope.items = [{
id:1,
propa:"one",
propb:"uno"
},{
id:2,
propa:"one",
propb:"uno"
},{
id:3,
propa:"two",
propb:"dos"
},{
id:4,
propa:"two",
propb:"dos"
}];
$scope.notGrouped = angular.copy($scope.items);
$scope.options = ['propa','propb'];
$scope.groupBy = function (option) {
$scope.items = _.groupBy($scope.notGrouped, option);
}
});
和相关的HTML模板
<body ng-app="MyApp">
<div ng-controller="MyCtrl">
Group by<br>
<select ng-model="selectedOption"
ng-options="option as option for option in options"
ng-change="groupBy(selectedOption)">
</select>
<br><br>
<div ng-hide="!!selectedOption">Not grouped yet...</div>
<div ng-repeat="item in items">
<span>{{ item | json }}</span>
</div>
</div>
</body>
会给你