javascript AngularJS 控制器取决于 URL 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14259739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:09:41  来源:igfitidea点击:

AngularJS Controller depending on URL parameter

javascriptangularjs

提问by billdangerous

EDIT:Added $routeProvider and $routeParams, but $routeParams.productId is always undefined. It was my initial try, but I thought it was the wrong way. Anyway it does not work for the moment.

编辑:添加了 $routeProvider 和 $routeParams,但 $routeParams.productId 始终未定义。这是我最初的尝试,但我认为这是错误的方式。无论如何它暂时不起作用。

I start to learn AngularJS and I have a very simple question : Depending on ID contained in URL, I would like to display different BD record.

我开始学习 AngularJS,我有一个非常简单的问题:根据 URL 中包含的 ID,我想显示不同的 BD 记录。

...
<div ng-app=MyApp>
  <div ng-controller="MyCtrl">
    {{ record }}
  </div>
</div>
...

My Javascript file :

我的 Javascript 文件:

var MyApp = angular.module("MyApp",[]);

MyApp.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/get/:productId', {
       controller: 'MyCtrl'
    });
}])

MyApp.controller('MyCtrl',['$scope','$routeParams','$http',
  function($scope,$routeParams,$http) {
     $http.get("/get/"+$routeParams.productId).success(function(data) {
        $scope.record = data;
     });
}])

I tried to use $routeProvider and $routeParams without success.

我尝试使用 $routeProvider 和 $routeParams 没有成功。

Thank you in advance, Bill

提前谢谢你,比尔

回答by mpm

you need 2 things , the $routeParams injected in your controller and create a valid route with the get method

你需要两件事,在你的控制器中注入的 $routeParams 并使用 get 方法创建一个有效的路由

    MyApp.controller('MyCtrl',['$scope','$http',"$routeParams",
        function($scope,$http,$routeParams) {
             $http.get("/get/"+$routeParams.productId).success(function(data) {
                 $scope.record = data;
        });
    };