如何使用角度控制器当前网址参数 [英] How to use current url params in angular controller

查看:131
本文介绍了如何使用角度控制器当前网址参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在URL中的动态值PARAMS和我想要得到它,当onload事件中使用的控制器
但我不知道如何应对 $ route.current.params

I have a dynamic value params in url and I want to get it and use in controller when onload But I have no idea how to deal with $route.current.params

让说我有这条路线提供商

Let say I have this route provider

$routeProvider.when('foo/:bar', {templateUrl: 'template.html'};

然后在我的控制器

Then in my controller

app.controller('mapCtrl', function($scope, $route, $routeParams) {

  var param = $route.current.params.bar;
  console.log(param);

});

如果用户访问富/ ABCDEFG 假设应显示在控制台ABCDEFG,但我得到了错误。
无法读取属性''未定义PARAMS

If user access foo/abcdefg suppose should show abcdefg in console but I got error. 'Cannot read property 'params' of undefined'

推荐答案

例如:

在你app_route.js你必须URL模式链接到一个特定的控制器和用于显示DATAS模板:

In you app_route.js you have to link url pattern to a specific controller and the template to use for displaying datas:

angular.module('mapApp', []).
    config(['$routeProvider', function($routeProvider){ 
                $routeProvider.when('/foo/:bar', {templateUrl: './view/partial/template.html', controller: mapCtrl});
                $routeProvider.otherwise({redirectTo: '/foo/01'});
            }
            ]);

在您的特定的控制器添加逻辑(由巴这里选择数据):
同样使用$ routeParams&安培; $ route.current.params

In your specific controller you add the logic (here select data by bar) : Same using for $routeParams & $route.current.params

function mapCtrl($scope, $routeParams, $http) {
    $http.get('./data/myDatas.json').success( function(data){
                                        var arr = new Array();
                                        for(var i=0; i < data.length; i++){
                                            if(data[i].bar == $routeParams.bar){
                                                arr.push(data[i]);                              }
                                            }
                                        $scope.items = arr;
                                        });
}
 mapCtrl.$inject = ['$scope', '$routeParams', '$http']; //for minified bug issue

而在你的template.html,布局:

And in your template.html, the layout :

<div ng-repeat="item in items">
    <h3>{{item.bar}}</h3>
</div>

不要忘了添加你想要展示你的DATAS索引页的NG-视图,NG-应用=mapApp在html标记。

Don't forget add the ng-view on your index page where you want displaying datas, and ng-app="mapApp" in html tag.

我希望这将有助于你^^

I hope that will help you ^^

有关更多的信息,请参阅: http://docs.angularjs.org/tutorial/step_07

for more informations, see : http://docs.angularjs.org/tutorial/step_07

这篇关于如何使用角度控制器当前网址参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆