2014-12-04 138 views
0

我有一個/tests中的測試表,我希望能夠通過去/tests/:id/hide來永久隱藏特定的測試。我有一個這樣做的函數,我只需要找出一個方法來調用它,而不必調用一個新的控制器。當這樣做時,我也想重新回到/tests重定向時的AngularJS調用函數

angular.module('WebApp.services', []). 
    factory('riakAPIService', function($http) { 
     var riakAPI = {}; 
     riakAPI.hideTest = function(key) { 
      return $http({ 
       // Some code for setting a "hide" flag for this test in the database 
      }); 
     } 
    }); 

有一個漂亮的方法來調用riakAPI.hideTest(id)當用戶進入/tests/:id/hide

angular.module('WebApp', ['WebApp.controllers','WebApp.services','ngRoute']). 
    config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { 
     $routeProvider. 
      when("/tests", {templateUrl: "partials/tests.html", controller: "testsController"}). 
      when("/tests/:id", {templateUrl: "partials/test.html", controller: "testController"}). 
      otherwise({redirectTo: '/tests'}); 
    }]); 

回答

1

我認爲最好的方法是使用這裏的解析參數。

$routeProvider.when('/tests/:id',{ 
    templateUrl : 'partials/tests.html', 
    controller : 'testController', 
    resolve : { 
     hidden : function(riakAPIService){ 
       return riakAPIService.hideTest(); 
     } 
    } 
}) 

而對於服務

angular.module('WebApp.services', []). 
    factory('riakAPIService', function($http,$location) { 
     var riakAPI = {}; 
     riakAPI.hideTest = function(key) { 
      return $http({ 
       // Some code for setting a "hide" flag for this test in the database 
      }).then(function(){ 
       $location.path('/tests'); 
      }); 
     } 
    });