我在下面用我的控制器拉入一个JSON对象,但是如何在每次页面刷新时使命令随机?
app.controller('MainCtrl', ['$scope', '$http', 'makeRandom', function ($scope, $http, makeRandom) {
$http.get('projects/projects.json').success(function(data) {
$scope.works = data;
});
makeRandom.forEach($scope.works, function(work) {
work.rank = Math.random();
});
}]);
template.html
<section ng-repeat="work in works | orderBy:'rank'" class="showcase {{work.class}}">
...
</section>
答案 0 :(得分:1)
你几乎完成了所有的工作,你只需要把它放在一起:
这是基于你的工作:
app.controller('myCtrl', ['$scope', '$http', function($scope, $http){
$http.get('projects/projects.json').success(function(data) {
$scope.works = data;
}).error(function(){
// works on error response because I don't have your code, just copy this to success response
// here I just generate a list of ids and then randomize them
var works = [];
for(var i=0; i< 20; i++){
works.push({id: i});
}
$scope.works = makeRandom(works);
});
function makeRandom(inputArray){
angular.forEach(inputArray, function(value){
value.rank = Math.random();
});
return inputArray;
}
}]);
HTML:
<section ng-repeat="work in works | orderBy:'rank'" class="showcase {{work.class}}">
{{work.rank}} {{work}}
</section>
以下是一个工作示例:http://plnkr.co/edit/xIwD0zWdodnYSIupm1va?p=preview