这可以通过创建两个具有相同 URL 的状态来实现。
对于打开模式的状态,创建一个隐藏参数,使用params 选项。这用于查找用户点击或直接点击的天气。如果用户是通过点击来的,那么我们通过ui-sref 为隐藏参数设置一个值并显示模态(使用 UI Bootstrap 的 $modal)。如果用户直接访问 URL,那么我们将他们重定向到具有相同 URL 但不同模板和控制器的另一个状态。所有这些都是在onEnter 函数中完成的,该函数在此状态打开时被调用。由于此状态没有 template 或 templateUrl ,因此它不会改变视图。
状态配置
.state('gallery', {
url: "/",
templateUrl: "gallery.html",
controller: 'galleryCtrl'
})
.state('gallery.photoModal', {
url: "photo/:id",
params: {
fromGallery: null
},
onEnter: ['$stateParams', '$state', '$modal', function($stateParams, $state, $modal) {
if ($stateParams.fromGallery === true) {
console.log('Goes To Modal View');
$modal.open({
templateUrl: 'modal.html',
controller: 'modalCtrl',
size: 'lg'
}).result.finally(function() {
$state.go('gallery'); // Parent state
});
} else {
console.log('Goes To Full View');
$state.go('gallery.photoFull', {
id: $stateParams.id
});
}
}],
onExit: ['$modalStack', function($modalStack) {
// Dismisses Modal if Open , to handle browser back button press
$modalStack.dismissAll();
}]
})
.state('gallery.photoFull', {
url: 'photo/:id',
templateUrl: "photo.html",
controller: 'photoCtrl'
})
父状态的模板,我们点击显示模态的地方
<div class="spacing" ui-view>
<div class="contain" >
<div ng-repeat='photos in gallery.photos'>
<a ui-sref="gallery.photoModal({id: photos.id,fromGallery:true})">
<img ng-src="{{photos.photoURL}}" width="200" height="200" />
</a>
</div>
</div>
</div>
父控制器,包含用于ngRepeat的虚拟数据
.controller('galleryCtrl', ['$scope', function($scope) {
$scope.gallery = {
photos: [{
photoURL: 'https://placeholdit.imgix.net/~text?txtsize=40&txt=200%C3%97200&w=200&h=200',
id: '1'
}]
};
}])
模态状态的模板
<div class="spacing">
<a ng-click="dismiss.modal()" class="pull-right" href>Close</a>
<img ng-src="{{photo.photoURL}}" width="500" height="500" />
</div>
模态状态控制器,包含关闭模态和虚拟数据的方法
.controller('modalCtrl', ['$scope', '$modalInstance', function($scope, $modalInstance) {
$scope.dismiss = {
modal: function() {
$modalInstance.dismiss('cancel');
}
};
$scope.photo = {
photoURL: 'https://placeholdit.imgix.net/~text?txtsize=80&txt=500%C3%97500&w=500&h=500',
id: '1'
};
}])
您可以在 Plunker 查看工作示例,查看 http://run.plnkr.co/plunks/wRqwPr/#/ 以查看 URL 的更改