只是學習角度,所以請原諒這個問題noob性質。 。 。ng-repeat過濾器沒有更新範圍變化
我有我想過濾的帖子列表,按字母順序或基於年齡(最早的第一個或最年輕的第一個)。我的代碼在我將html移動到指令模板之前正在工作。現在不是。很明顯,我錯過了消化週期的一些東西。
看看這plunker看到的問題在行動。正如你所看到的,$ scope.predicate和$ scope.reverse都被更新,但是過濾器不會被重新觸發。
HTML:
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body>
<div posts></div>
</body>
JS:
var app = angular.module('myApp', []);
app.controller('postsCtrl', ["$scope", function($scope) {
function getPosts() {
return [{
"title": "bbbBloter",
"createdOn": new Date()
}, {
"title": "cccBloter",
"createdOn": new Date(1360000000000)
}, {
"title": "aaaBloter",
"createdOn": new Date(1290000000000)
}, {
"title": "dddBloter",
"createdOn": new Date(1390000000000)
}, {
"title": "abcBloter",
"createdOn": new Date(1280000000000)
}, ];
}
//load each blotter, then get each blotters' posts, and then set-up the blotter init values
function init() {
$scope.posts = getPosts();
$scope.predicate = 'story.last_posting';
$scope.reverse = true;
$scope.orderProp = "last_posting";
}
//user has requested a different sorting
$scope.changeSort = function(sortingOn) {
switch (sortingOn) {
case "title":
$scope.predicate = 'story.title';
$scope.reverse = false;
break;
case "last_posting":
$scope.predicate = 'story.last_posting';
$scope.reverse = true;
break;
case "first_posting":
$scope.predicate = 'story.last_posting';
$scope.reverse = false;
break;
}
};
init();
}]);
app.directive('posts', function($filter) {
return {
replace: true,
template:
'<div ng-controller="postsCtrl">' +
'<div>' +
'Search: <input ng-model="query">' +
'Sort by:' +
'<select ng-model="orderProp" ng-change="changeSort(orderProp)" >' +
'<option value="title">Alphabetical</option>' +
'<option ng-selected=true value="last_posting">Newest</option>' +
'<option value="first_posting">Oldest</option>' +
'</select>' +
'<br>predicate:{{predicate}}; reverse:{{reverse}}<br>' +
'<ul>' +
'<li debug ng-repeat="post in posts | filter:query | orderBy:predicate:reverse">' +
'{{post.title}}' +
'<p>{{post.createdOn}}</p>' +
'</li>' +
'</ul>' +
'</div>' +
'</div>',
link: function(scope){
scope.$watch("reverse", function(){
console.log(scope);
});
}
};
}
);
僅供參考,最好在這裏發表您的代碼。 – SomeKittens
嘗試簡化SO的代碼時犯了一個錯字。我會再試一次,並重新發布爲一個新問題。感謝所有爲你的時間做出迴應的人! –