我想知道,有什么方法可以通过对象或函数引用状态吗?
只是为了使视图与状态定义脱钩。例如,如果我更改州名,则不必在我的视图中的任何地方更改它。
可以在这里找到一种解决方案,如下所述,它可以作为工作中的活塞
在此示例中,我们将为某些实体(例如员工)定义状态,例如:
让我们使用一些变量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;
};
}],
就是这样。甚至可能更加复杂...完整的示例代码(以下定义为状态)可以在此处找到并运行
.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];
}],
}
}});
}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句