如何在Angular JS中的routeProvider中传递param?

Ham*_*med 5 angularjs

我在Angular JS中使用routeProvider:

.when('/profile/personal', {
       templateUrl: 'personal.html',
       controller: 'EditProfileController'
})
Run Code Online (Sandbox Code Playgroud)

我如何将param传递给控制器EditProfileController,这里调用返回数据的Ajax方法.此数据必须显示在路径模板中personal.html.

例:

    .controller('EditProfileController', ['$scope', '$http', function ($scope, $http) {
         // If was click on `/profile/personal` from route, must get patam `personal` and call method GetAjax(param);
         $scope.GetAjax = function (param){
            //here return data put it in template HTML from route
         }  

    }]);
Run Code Online (Sandbox Code Playgroud)

我的链接位于页面路径中:

http://wd.tk/profile

当我点击链接路线时,我得到了URL:

http://wd.tk/profile#/profile/personal/1

我会做:

.controller('EditProfileController', ['$scope', '$http', function ($scope, $http, $routeParams) {
   console.log($routeParams);
}]);
Run Code Online (Sandbox Code Playgroud)

我收到错误:

TypeError: Cannot read property 'idProfile' of undefined
Run Code Online (Sandbox Code Playgroud)

小智 8

首先,在你的url配置中,你必须输入url的参数:

when('/profile/personal/:idProfile', {
       templateUrl: 'personal.html',
       controller: 'EditProfileController'
})
Run Code Online (Sandbox Code Playgroud)

现在,在EditProfileController中,您应该获取参数并调用ajax请求:

注入$ routeParams对象并获取参数

$routeParams.idProfile:

.controller('EditProfileController',  
function ($scope, $http, $routeParams) {

   var idProfile = $routeParams.idProfile;

   $http.get("service url").then(setData, setError);

   function setData(data) {
       $scope.data = data;
   }
   function setError() {
       alert("error on get data profile");
   }

}]);
Run Code Online (Sandbox Code Playgroud)

在您的html中,您将以正确的格式显示您的数据配置文件.

但我建议所有的ajax调用都应该在angular服务中进行分组.PD:检查角度ui路由器:

angular-route和angular-ui-router之间有什么区别?

希望这可以帮助.