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

前端之家收集整理的这篇文章主要介绍了angularjs – 如何在Angular JS中的routeProvider中传递param?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Angular JS中使用routeProvider:

.when('/profile/personal',{
       templateUrl: 'personal.html',controller: 'EditProfileController'
})

我如何将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
         }  

    }]);

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

http://wd.tk/profile

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

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

我会做:

.controller('EditProfileController',$http,$routeParams) {
   console.log($routeParams);
}]);

我收到错误

TypeError: Cannot read property 'idProfile' of undefined

解决方法

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

when('/profile/personal/:idProfile',controller: 'EditProfileController'
})

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

注入$routeParams对象并获取参数

$routeParams.idProfile:

.controller('EditProfileController',$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");
   }

}]);

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

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

What is the difference between angular-route and angular-ui-router?

希望这可以帮助.

猜你在找的Angularjs相关文章