【问题标题】:How to change the location to open another page in Angular?如何更改位置以在 Angular 中打开另一个页面?
【发布时间】:2016-10-24 00:02:19
【问题描述】:

我的问题是如何使用 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被调用时改变页面。

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:
    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 -->
    
        });
      }
    }]); 
    

    【讨论】:

      【解决方案2】:

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

      Angular 有$location 服务,但是对于构建应用程序,我建议您使用路由库。连 Angular 团队都推荐使用ui-router

      【讨论】:

        【解决方案3】:

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

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

        如本答案所述:

        https://stackoverflow.com/a/27941966

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

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

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

        【讨论】:

          猜你喜欢
          • 2014-01-24
          • 2011-04-06
          • 1970-01-01
          • 1970-01-01
          • 2021-08-30
          • 1970-01-01
          • 1970-01-01
          • 2011-12-13
          • 1970-01-01
          相关资源
          最近更新 更多