我是Angular的新手。我正在使用控制器,我最初使用init函数加载页面。我在html上有一个元素来激活incrementPage函数。当我激活该函数时,init函数再次执行,我得到的结果与下一页相同。我该如何解决这个问题?
myApp.controller('MusicController', ['$scope', '$resource', function($scope, $resource){
var vm = $scope;
init();
function init(){
vm.pgno = 1;
music = $resource('http://104.197.128.152:8000/v1/tracks/', {"page": vm.pgno}).get({"page": vm.pgno});
vm.tracks = music;
}
vm.incrementPage = function(){
vm.pgno = vm.pgno + 1;
console.log(vm.pgno);
music = $resource('http://104.197.128.152:8000/v1/tracks/', {"page": vm.pgno}).get({"page": vm.pgno});
vm.tracks = music;
console.log(vm.pgno);
};
}]);
另外,我正在使用ngRoute和两个不同的控制器。
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "views/listMusic.html",
controller:'MusicController',
})
.when('/genres', {
templateUrl: "views/genres.html",
controller:'MusicGenreController',
})
}]);
myApp.controller('MusicGenreController', ['$scope', 'tracklister', function($scope, tracklister) {
var vm = $scope;
var gpgno = 1;
var incrementGPage = function(){
gpgno += 1;
gen = tracklister.genreList.get({'page': gpgno});
vm.genres = gen;
}
(function(){
gen = tracklister.genreList.get({'page': gpgno});
vm.genres = gen;
})();
}]);
当我点击<a href="#genres">Genres</a>
而不是将我带到流派视图时,它会让我回到第一个MusicController
控制器内的同一个listMusic视图。该怎么办?
<!DOCTYPE html>
<html ng-app='ListTracksApp'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-resource.js"></script>
<script src="appl.js"></script>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<title>Music</title>
</head>
<body>
<h1>Music Tracks</h1>
<a href="#genres">Genres</a>
<div ng-view>
</div>
</body>
</html>
答案 0 :(得分:0)
在您的控制器中,将其更改为:
myApp.controller('MusicController', ['$scope', '$resource', function($scope, $resource) {
var vm = $scope;
function $onInit() {
// the rest of your code
当控制器初始化时,它会被调用一次。另外我认为你的链接不正确,正如georgeawg所指出的那样,但我对ngRoute不太熟悉,我已经使用了uiRouter多年,它应该是#!/ genres
另一件事虽然这与你的问题没有关系,但在你的init()函数中你调用了你的db,我怀疑它是异步的,你应该在ngRoute中使用resolve将其注入控制器,以便最初解决:
resolve: {
data: function ($resource) {
var url = 'http://104.197.128.152:8000/v1/tracks/';
return $resource(url, {"page": 1}).get({"page": 1}).$promise;
}
}
然后您的控制器可以使用&#39;数据&#39;作为电话的结果:
myApp.controller('MusicController', ['$scope', '$resource', 'data', function($scope, $resource, data)