2014-10-09 36 views
0

AngularJS noob here。AngularJS:我如何在URL中获得散列值

我希望我的应用程序能够响应网址哈希。通过回应,我的意思是设置一个变量值等简单的东西。

在这个例子中,如果该URL为HTTP:example.com/#parents-to-be,我希望应用程序执行的标准行为是滚动到#父母将要,并且还设置了$ scope.tab3 = 1;

从做一些研究,似乎这样才能与$的location.hash()$ anchorScroll()的组合来实现。但是,迄今为止我还没有取得成功。有人可以帮忙吗?

HTML:

<div ng-app="bug"> 
    <div ng-controller="TabsController"> 
     <a href ng-click="activateTab(1)">tab 1</a> 
     <a href ng-click="activateTab(2)">tab 2</a> 
     <a href ng-click="activateTab(3)">tab 3</a> 

     <div id="parents-to-be"> <!-- this is the target div --> 
      <div ng-show="tab1 === 1">content of tab 1</div> 
      <div ng-show="tab2 === 1">content of tab 2</div> 
      <div ng-show="tab3 === 1">content of tab 3</div> 
     </div> 

    </div> <!-- /angular tabs controller scope -->  
</div> <!-- /angular app scope --> 

app.js:

(function() { 
     var app = angular.module('bug', []); 
     app.controller('TabsController', function($scope, $location, $anchorScroll) { 
      // init tabs 
      $scope.initTabs = function() { 
       $scope.tab1 = 0; 
       $scope.tab2 = 0; 
       $scope.tab3 = 0; 
      }; 
      // activate tabs 
      $scope.activateTab = function(tab_index) { 
       $scope.initTabs(); 
       $scope['tab' + tab_index] = 1; 
      }; 
      // this is the part of the app where I try to get the hash value and edit the value of tab3 
      $scope.hash_value = $location.hash(); 
      if ($scope.hash_value === "parents-to-be") { 
       $scope.activateTab(3); 
       $anchorScroll(); 
      } 
     }); 
    })(); 

谢谢!

+0

使用'$ location.search()' – Amy 2014-10-09 07:42:36

回答

0

使用$on事件处理$locationChangeSuccess事件后捕获的哈希值:

$rootScope.$on('$locationChangeSuccess', function() 
{ 
console.log(arguments[1].replace(/[^#]+(#.+)/, "$1")); 
} 
) 

angular.element(document).injector().get('$rootScope').$on('$locationChangeSuccess', function(){console.log(arguments[1].replace(/[^#]+(#.+)/, "$1"))}) 

参考