简体   繁体   中英

How to change the location to open another page in Angular?

My question is how do I change the URI with Angular. In other words, when a function is called I would like to change the page.

Here is my angular code

app.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
  var Meetup = $resource('/api/meetups');

  Meetup.query(function (results) {
    $scope.meetups = results;
  });

  $scope.meetups = []

  $scope.createMeetup = function () {
    var meetup = new Meetup();
    meetup.name = $scope.meetupName;
    meetup.$save(function (result) {
      $scope.meetups.push(result);
      $scope.meetupName = '';
    });
  }
}]);  

I would like to change the page when the function createMeetup is called.

You can set a new url for the browser using:

$window.href.location = 'http://...'

as discussed in this answer:

https://stackoverflow.com/a/27941966

As Gregório Kusowski mentioned, using ui-router is recommended for advanced routing or creating a SPA (single page application). Normally it is not necessary to navigate to a whole new URL for creating a new object (meeting, user, etc)

Note: put $window.href.location statement inside your $save "callback function". If you put it outside, your page will change, but your meetup data may not have time to save.

Also note that changing the page this way will erase your scope variables and everything else. It will be as if you refreshed the page. I'm sure that's not what you want. Read about ui-router for best results.

The simplest way is to use window.location = '...';

Angular has the $location service, but for structuring an app, I would recommend you to use a routing lib. Even the angular team recommend the use of ui-router .

app.controller('meetupsController', ['$location,$scope', '$resource', function ($location,$scope, $resource) {
  var Meetup = $resource('/api/meetups');

  Meetup.query(function (results) {
    $scope.meetups = results;
  });

  $scope.meetups = []

  $scope.createMeetup = function () {
    var meetup = new Meetup();
    meetup.name = $scope.meetupName;
    meetup.$save(function (result) {
      $scope.meetups.push(result);
      $scope.meetupName = '';
$location.path('/newValue') <!-- it should be the path you want -->

    });
  }
}]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM