因此,如果我的數據來自JSON $ http,我該如何做到這一點,如果我點擊一個控制器上的投票,它會按順序排序另一個控制器上的投票?
我有什麼到目前爲止心不是正確的工作,它看起來像共享數據並捕獲控制器之間的任何變化......把它看
app.controller('voteController', function ($scope, musicData) {
musicData.getMusic().then(function(data){
$scope.music = data.data;
});
$scope.upVote = function(music) {
music.likes++;
};
$scope.downVote = function(music) {
music.dislikes--;
};
});
// controller for top 5 charts
app.controller('topFiveController', function ($scope, musicData) {
musicData.getMusic().then(function(data){
$scope.music = data.data;
});
$scope.sortorder = '-likes';
});
// factory to share data between controllers
app.factory('musicData', function($http) {
var factory = {};
factory.getMusic = function() {
return $http.get('app/data/music.json');
};
return factory;
});
,這就是我在標記
<div id="topMusic" ng-controller="topFiveController" ng-model="sortorder">
<h3 class="title"><i class="fa fa-hand-o-right"></i> Top 5 titles</h3>
<ul>
<li ng-repeat="music in music.music | orderBy:sortorder | limitTo: 5">
{{music.artist}} - "{{music.title}}"
</li>
</ul>
</div>
<div id="voteMusic" ng-controller="voteController">
<h1>Vote here</h1>
<ul>
<li class="likeMe" ng-click="upVote(music)">
<i class= "fa fa-thumbs-up" ></i> like - {{music.likes}}</li>
<li class="dislikeMe" ng-click="downVote(musics)">
<i class="fa fa-thumbs-down"></i>dislikes -
{{music.dislikes}}</li>
</ul>
</div>
這是JSON文件看起來像
{"music": [
{
"artist": "Artst 1",
"title": "title one",
"likes": 10,
"dislikes": 1
},
{
"artist": "Artst 2",
"title": "title 2",
"likes": 5,
"dislikes": 1
},
{
"artist": "Artst 3",
"title": "title 3",
"likes": 3,
"dislikes": 1
},
{
"artist": "Artst 4",
"title": "title 4",
"likes": 2,
"dislikes": 1
},
{
"artist": "Artst 5",
"title": "title 5",
"likes": 1,
"dislikes": 1
}
]
}
我們需要查看您的musicData服務以瞭解其工作原理。簡單的方法是在'topFiveController'內的'music.getMusic()'上放置'$ watch',但這可能會對您的應用程序帶來性能影響。 – 2014-10-08 17:16:13
謝謝!我剛剛編輯了我的帖子,並添加了如何設置json對象。 – tweb 2014-10-08 17:24:22