如何在AngularJS中隐藏URL中的选择性数据

时间:2016-04-11 13:02:08

标签: javascript angularjs angular-ui-router

我正在为AngularJs中的SPA编写代码。我在此使用ui-router代替ngRoute来进行路由和控制导航。在我的应用程序中,有一种情况是我通过url传递userId以编辑该特定用户的信息。

我针对特定案例的路由如下:

.state('user-edit', {
  url: '/users/:uId/:operation',
  templateUrl: 'views/user.html',
  controller: 'UserCtrl'
})

我的相关标记是:

<td><a ng-href='#/users/{{user.id}}/edit'><img src="images/edit-icon20.png"></a></td>

我的控制器的一部分:

if ($stateParams.operation == 'edit'){ 
   *My Logic*
}

我的网址现在显示为:

http://localhost:8080/#/users/3/edit

问题:
在此网址或此类网址中,我不希望用户看到我的用户ID。我要么将它显示为别的东西,要么我希望它完全隐藏。我已经在Stackoverflow上找到了问题AngularJS: How to clear query parameters in the URL?,但帮助我,因为我的网址格式不同。

问题
我需要将该userID传递给REST调用。那么我该如何隐藏它或者加扰呢?

1 个答案:

答案 0 :(得分:1)

var app = angular.module('plunker', []); 

app.controller('main',['$scope', 'dataService', function($scope, dataService) {
  $scope.numbers = [];
  console.log(dataService);
  //is getNumbers a function?
  dataService.getNumbers(0, 20).then(function(numbers){
    $scope.numbers = numbers;
  });
}]);

app.factory('dataService', ['$q', function($q) {
  console.log('construct service');
  var dataService = this;
  
  // factory function body that constructs shinyNewServiceInstance
  var numbers = [];
  dataService.getNumbers = function(i, m){ 
    var s = i;
    var deferred = $q.defer();
    console.log('Data retrieval fired: ' + i + ' to ' + m);
    while(i < s + m){
      numbers.push(i++);
    }
        setTimeout(function(){
          console.log('Data retrieval complete');
          deferred.resolve(numbers);
      },100);
      
    
    console.log('Promise returned');
    return deferred.promise; 
  };
  
  return dataService;
}]);
<html>

  <head>        
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
  </head>

  <body ng-app="plunker" ng-controller="main">
      <div>
        <ul>
          <li ng-repeat="n in numbers">Number: {{n}}</li>
        </ul>
      </div>
  </body>
</html>

创建将维护您正在编辑的当前所选用户的服务。

var app = angular.module('{you user module name}'); 

app.factory('userService', ['$q', function($q) {
  console.log('construct service');
  var userService= this;
  // factory function body that constructs shinyNewServiceInstance
  userService.selectedUser = null; //will set this when editing
  userService.setUser = function(userId){
     //let's assume that you can get the user based on id 
     selectedUser = getUser(userId); 
  };
  //Other properties and functions that make up your user service

  return userService;
}]);

其他地方:

userService.setUser($stateParams.userId); //we've set the user 
$location.url('/edituser'); //or however you want to change the current url