在AngularUI Router中是否有可能实现自动滚动而不改变状态?

10 浏览
0 Comments

在AngularUI Router中是否有可能实现自动滚动而不改变状态?

我正在使用AngularUI Router和Bootstrap。我在同一个状态下有两个视图,并且希望在点击按钮时滚动到第二个视图。当初始状态和视图加载时,我不需要进行任何滚动。当点击“Add More”按钮时,我希望页面滚动到#start。我尝试使用$anchorScroll来实现这一点,但没有成功。有什么好的建议吗?

HTML:



 添加更多

控制器的Javascript代码:

myApp.controller('SelectionListCtrl', function (Selections, $location, $anchorScroll) {
    var selectionList = this;
    selectionList.selections = Selections;
    this.selectedServices = Selections;
    selectionList.gotoBottom = function() {
     $location.hash('start');
     $anchorScroll();
     };
  });

路由的Javascript代码:

myApp.config(function ($stateProvider, $urlRouterProvider, $uiViewScrollProvider) {
    $uiViewScrollProvider.useAnchorScroll();
    $urlRouterProvider.otherwise('/');
    $stateProvider
      .state('selection', {
              url: '/selection',
              views: {
                  'list': {
                      templateUrl: 'views/list.html',
                      controller: 'ProjectListCtrl as projectList'
                  },
                  'selectionlist': {
                      templateUrl: 'views/selectionlist.html',
                      controller: 'SelectionListCtrl as selectionList'
                  }
              }
              })

0
0 Comments

是的,可以在AngularUI Router中实现自动滚动而不改变状态。

问题的原因是调用滚动函数时使用了ng-click="gotoSection()"而不是ng-click="gotoBottom()"。另外,gotoBottom()函数的定义必须在ProjectListCtrl中,而不是SelectionListCtrl中。这是因为gotoBottom()的调用发生在列表视图中,而$stateProvider中定义gotoBottom()的控制器必须是列表视图所在的控制器。

下面是两种实现目标的方法:

1. 在控制器ProjectListCtrl中注入$scope,然后在同一个控制器中定义$scope.gotoBottom函数。

app.controller('ProjectListCtrl', function ($location, $anchorScroll,$scope) {
  var selectionList = this;
  $scope.gotoBottom = function() {
    console.log("go to bottom");
    $location.hash('start');
    $anchorScroll();
  };
});

list.html视图中,可以使用gotoBottom()来调用$scope.gotoBottom函数:ng-click="gotoBottom()"

2. 或者使用controller as语法,例如ProjectListCtrl as projectList

this.gotoBottomWithoutScope = function(){
  $location.hash('start');
  $anchorScroll();
};

使用这种语法,在ProjectListCtrl中使用this.gotoBottomWithoutScope,但在视图中必须引用为projectList.gotoBottomWithoutScope()

请参考上面提供的链接和示例来了解更多关于this$scope的知识。

这正是我要找的。非常感谢提供额外的链接和示例。谢谢!

0