簡體   English   中英

Angular:將$ routeProvider中的參數傳遞給控制器

[英]Angular: Passing params from $routeProvider to controller

我有多個路由調用相同的控制器,我想傳遞不同的變量。

// Example
$routeProvider.
  when('/a', {
    templateUrl: 'test.html',
    controller: 'MyController' // should get passed 'exampleA'
  }).
  when('/b', {
    templateUrl: 'test.html',
    controller: 'MyController' // should get passed 'exampleB'
});

我知道我可以使用“resolve”對象:

$routeProvider.
  when('/a', {
    templateUrl: 'test.html',
    controller: 'MyController',
    resolve: {test: function() { return true; }}
});

要將值作為依賴項傳遞:

app.controller('MyController', ['$scope', 'test', function ($scope, test) {
  console.log(test); // true
}

我的問題是我的應用程序崩潰,如果在其他路由上缺少resolve對象,我想傳遞可選參數。

有沒有辦法將特定參數傳遞給Controller(來自路由提供商)?


謝謝

路由:

$routeProvider.
  when('/a', {
    templateUrl: 'test.html',
    controller: 'MyController',
    paramExample: 'exampleA'
  }).
  when('/b', {
    templateUrl: 'test.html',
    controller: 'MyController',
    paramExample: 'exampleB'
});

訪問:在您的控制器中注入$ route然后使用它

 app.controller('MyController', ['$scope', '$route', function ($scope, $route) {
      var paramValue = $route.current.$$route.paramExample;
      console.log(paramValue); 
 }

你可以使用resolve和$route.currrent.params.test來傳遞這樣的參數:

$routeProvider
  .when('/a', {
    templateUrl: 'view.html',
    controller: 'MainCtrl',
    resolve: {
        test: function ($route) { $route.current.params.test = true; }
    }
  })
  .when('/b', {
    templateUrl: 'view.html',
    controller: 'MainCtrl',
    resolve: {
        test: function ($route) { $route.current.params.test = false; }
    }
  })

然后在您的控制器中,您可以從$ routeParams訪問它:

app.controller('MainCtrl', function($scope, $routeParams) {
  $scope.test = $routeParams.test;
})

http://plnkr.co/edit/ct1ZUI9DNqSZ7S9OZJdO?p=preview

最自然的方法是執行您希望加載帶有參數的頁面時通常會執行的操作:使用查詢參數:http: http://yoururl.com?param1=value&param2=value

ngRoute附帶了服務$ routeParams,您可以在控制器中注入該服務。 現在你可以簡單地檢索像$routeParams.param1這樣的值。

另一種方法是使用$location.path檢索路徑並在那里設置變量。

使用$ routeParams

在主js文件中

routeApp.config(function($routeProvider) {
$routeProvider
    .when('/home', {
        templateUrl: '../sites/./home.html',
        controller: 'StudentController'
    })
    .when('/viewStudents/:param1/:param2', {
        templateUrl: '../sites/./viewStudents.html',
        controller: 'StudentController'
    })
    .otherwise({
        redirectTo: '/'
    });
 });

 routeApp.controller('StudentController',['$filter','$routeParams', '$location',function($filter,$routeParams,$location){
   var StudentCtrl = this;  
   StudentCtrl.param1 = $routeParams.param1;
   StudentCtrl.param2 = $routeParams.param2;
 }]);

從Home.html打電話

 <div class="container">
   <h2> Welcome </h2>
   <a href="#/viewStudents/myname/somevalue2">Students</a>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM