更改URL时绑定到数据
问题描述:
我正在构建使用ui路由器的应用程序。在我的/团队路线上,我有一个表单,用户可以添加一个团队名称,然后将名称推送到我的MongoDB并绑定到视图并显示团队名称,其中包含多个选项,其中一个是链接到页面的按钮可以为团队添加更具体的信息。我的路由工作在这方面,例如,url显示为/#/teams/oklahoma
或/#/teams/washington
。这里是我的路由是什么样子:更改URL时绑定到数据
app.config(
['$stateProvider','$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/');
.state('teams', {
url: '/teams',
templateUrl: './templates/main/league.html',
controller: 'leagueCtrl'
})
.state('teams/:title', {
url: '/teams/:title',
templateUrl: './templates/main/team.html',
controller: 'teamCtrl'
})
这里是我的链接/teams/:title
路线:
<a href="#subjects/{{ team.title | lowercase }}">
<button ng-click="viewTeam(team)" class="team-button">View</button>
</a>
目前我没有在我的viewTeam()函数的任何信息。我的问题是,如何在新视图中使用新网址绑定到我的{{team.title}}和其他相关信息?我知道一个工厂必须以某种方式参与进来,并且我尝试了在http://onehungrymind.com/angularjs-communicating-between-controllers/上描述的解决方案,但没有成功。任何额外的指导将非常感激。
答
该URL可能应包含团队ID。我将假设你的'团队'数组是使用来自后端API的$ http加载的。
app.config(
['$stateProvider','$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/');
.state('teams', {
url: '/teams',
// the `teams` state will wait to load until $http.get() call is completed.
// this resolve declaration will provide the resulting teams array as an injectable 'teams' object.
resolve: { teams: function($http) { return $http.get("/teams.json"); },
templateUrl: './templates/main/league.html',
// This simplified controller injects the 'teams' resolve and simply sticks the list of teams on the scope to ng-repeat etc.
controller: function($scope, teams) { $scope.teams = teams; }
})
// This is a nested state, called `teams.team`. It requires a `teamId` parameter.
// The parameter can be provided by a URL: http://localhost/app#/teams/9237594827
// The parameter can be provided by $state.go: $state.go('teams.team', { teamId: 9237594827 });
// The parameter can be provided by uiSref: <a ui-sref="teams.team({ teamId: repeatedTeam.id })">{{repeatedTeam.title}}</a>
.state('teams.team', {
// `teams.team` state declares a `teamId` state parameter in the URL
url: '/teams/:teamId',
// This resolve function uses $stateParams to locate the correct team from the list.
// `team` will be made available for injection
resolve: {
team: function($stateParams, teams) {
// Find the correct team from the `teams` array, by ID.
return teams.filter(function(team) { return team.id === $stateParams.teamId; })[0];
}
},
templateUrl: './templates/main/team.html',
// Inject the `team` resolve and put it on $scope
controller: function($scope, team) { $scope.team = team; }
})
league.html:
<ul>
<li ng-repeat="team in teams">
<a ui-sref="teams.team({ teamId: team.id })">{{team.title}}</a>
</li>
</ul>
如果您正在使用嵌套的意见的话,你的国家名称不正确,而不是团队/:标题,它应该是teams.title。 – 2014-10-06 15:33:43
我试过这个,但它导致.otherwise被触发并将我送回'/'。有没有办法做一个嵌套视图以外的东西? – gjanden 2014-10-07 17:15:54
我想要做的就是删除/ teams视图,并将其替换为仅点击一个团队的具体细节。 – gjanden 2014-10-07 17:50:50