可以在这里找到如下所述的一种解决方案,作为一种可行的解决方案plunker http://plnkr.co/edit/pujRy9eUeHnZInPuXT23?p=preview
在此示例中,我们将为某些实体(例如员工)定义状态,例如:
-
list查看和
-
detail view.
让我们使用一些变量entityName
起到解耦命名的作用:
var entityName = "employee";
$stateProvider
.state(entityName, {
url: '/' + entityName,
views: {
...
}})
.state(entityName + '.detail', {
url: '/{{Id}}',
views: {
...
}});
从列表导航到详细视图(正如我们所看到的,没有使用明确的“员工”名称):
<a ui-sref="{{detailLink(item)}}" >{{item.Name}}</a>
接下来我们必须定义detailLink(item)
。我们将直接在controller
在这里,但可能是一些ListModel
改为实例,封装更多操作(分页、排序), 包括detailLink
.
controller:['$scope','$state',
function ( $scope , $state){
$scope.detailLink = function (item){
// here we get the employee in run-time
var currentState = $state.current.name;
var sref = currentState + '.detail({Id:' + item.Id + '})';
return sref;
};
}],
就是这样。它可能会更复杂......完整的示例代码(如下所述定义)可以找到并运行here http://plnkr.co/edit/pujRy9eUeHnZInPuXT23?p=preview
.config(['$stateProvider',
function( $stateProvider) {
var entityName = "employee";
$stateProvider
.state(entityName, {
url: '/' + entityName,
views: {
body: {
template: '<div>' +
' <h2>List View</h2> ' +
' <ul ng-repeat="item in items"> ' +
' <li><a ui-sref="{{detailLink(item)}}" >{{item.Name}}</a>' +
' </li></ul>' +
' <h2>Detail View</h2> ' +
' <div ui-view="detail"></div>' +
'</div>',
controller:['$scope','$state',
function ( $scope , $state){
$scope.items = [{Name : "Abc", Id : 0}, {Name : "Def", Id : 1}];
$scope.detailLink = function (item){
var currentState = $state.current.name;
return currentState + '.detail({Id:' + item.Id + '})';
};
}],
}
}})
.state(entityName + '.detail', {
url: '/{{Id}}',
views: {
detail: {
template: '<div>' +
' <label>{{item.Name}} ' +
' <input ng-model="item.Name"}}" type="text" />' +
' <div>current state name: <i>{{state.name}}<i></div> ' +
'</div>',
controller:['$scope','$stateParams','$state',
function ( $scope , $stateParams , $state){
$scope.state = $state.current
$scope.item = $scope.items[$stateParams.Id];
}],
}
}});
}])