Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular UI-Router open modal window on url change

I use angular-ui-router and angular-bootstrap in my project.

I want to implement follow use case:

When user click to "edit" button, UI-Router change URL and open modal window. When I go back by click on browser's back button, modal window is closing.

If user reload page when modal window is opened, application should render modal window content in main ui-view container.

This use case you can see on this sire: http://canopy.co/ (try to click on item and reload page)

Question: How to implement behaviour described above?

Here is my jsFiddle http://jsfiddle.net/sloot/ceWqw/3/

var app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
.config(function ($stateProvider, $urlRouterProvider) {

  $urlRouterProvider.otherwise('/');
  $stateProvider
    .state('app', {
      url: '/',
      controller: 'AppCtrl',
      templateUrl: '/views/app.html'
    })
    .state('item', {
      url: '/profile',
      controller: 'ItemCtrl',
      templateUrl: '/views/item.html'
    });
})
.controller('AppCtrl', function($scope, $modal, $state){
  $scope.open = function(){

    // open modal whithout changing url
    $modal.open({
      templateUrl: '/views/item.html'
    });

    // I need to open popup via $state.go or something like this
  };
})
.controller('ItemCtrl', function(){});
like image 368
Anton Rodin Avatar asked Feb 08 '14 22:02

Anton Rodin


1 Answers

There is a great example here on the ui-router FAQs. The key is using the onEnter param.

https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-open-a-dialogmodal-at-a-certain-state

Here's an example of to do it using ui-bootstrap's $modal service. This example only specifies an onEnter function. There is no template, controller, etc. So essentially the modal is shown, then when its closed it returns to the items state. You are still responsible for handling what state your app transitions to when the modal closes.

$stateProvider.state("items.add", {
    url: "/add",
    onEnter: function($stateParams, $state, $modal, $resource) {
        $modal.open({
            templateUrl: "items/add",
            resolve: {
              item: function() { new Item(123).get(); }
            },
            controller: ['$scope', 'item', function($scope, item) {
              $scope.dismiss = function() {
                $scope.$dismiss();
              };

              $scope.save = function() {
                item.update().then(function() {
                  $scope.$close(true);
                });
              };
            }]
        }).result.finally(function() {
            $state.go('^');
        });
    }
});
like image 62
ofairfoul Avatar answered Nov 01 '22 02:11

ofairfoul