繁体   English   中英

如何更改位置以在 Angular 中打开另一个页面?

[英]How to change the location to open another page in Angular?

我的问题是如何使用 Angular 更改 URI。 换句话说,当一个函数被调用时,我想改变页面。

这是我的角度代码

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 = '';
    });
  }
}]);  

我想在调用函数createMeetup时更改页面。

您可以使用以下方法为浏览器设置新网址:

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

如本答案所述:

https://stackoverflow.com/a/27941966

正如 Gregório Kusowski 所提到的,建议使用 ui-router 进行高级路由或创建 SPA(单页应用程序)。 通常不需要导航到一个全新的 URL 来创建新对象(会议、用户等)

注意:将 $window.href.location 语句放在 $save “回调函数”中。 如果你把它放在外面,你的页面会改变,但你的聚会数据可能没有时间保存。

另请注意,以这种方式更改页面将删除您的范围变量和其他所有内容。 就像您刷新了页面一样。 我确定那不是你想要的。 阅读 ui-router 以获得最佳结果。

最简单的方法是使用window.location = '...';

Angular 有$location服务,但为了构建应用程序,我建议您使用路由库。 甚至 angular 团队也推荐使用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 -->

    });
  }
}]); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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