【问题标题】:Angularjs pass query parameterAngularjs传递查询参数
【发布时间】:2016-07-12 20:22:18
【问题描述】:

现在我正在调用下面的代码:

http://localhost:8081/cgi/#/home

它会将我带到我的主页。

我的 app.js 是:

angular.module('myModule', 
    ['ngRoute', 'ngCookies', 'ui.bootstrap', 
     'angularUtils.directives.dirPagination'])
.config([ '$routeProvider', function($routeProvider) {

$routeProvider.when('/index', {
    controller : 'homeController',
    templateUrl : './app/views/index.html',
})

.when('/', {
    controller : 'homeController',
    templateUrl : './app/views/home.html'
})

.otherwise({
    redirectTo : '/'
});
}])

现在我需要添加额外的参数“debug”,我可以将其存储在我的控制器中,如果存在我需要调用一些函数。

我已尝试将以下内容添加到我的 app.js 中

    .when('/debug', {
    controller : 'homeController',
    templateUrl : './app/views/home.html',
    })

下面一行到我的控制器

$scope.debug = $routeParams.debug === 'true' ? true : false;
console.log($scope.debug);

在我的控制器中:

var app = angular.module('myModule');
app.controller('homeController', function($scope, $http, $route) {
    $scope.debug = $routeParams.debug === 'true' ? true : false;
    console.log($scope.debug);
}

另外请包括您认为可以回答的网址,因为我可以理解从哪里开始寻找 routeProvider 或 $location 功能

但是页面现在已经停止加载,我不知道如何让它工作。 请帮忙

【问题讨论】:

    标签: javascript angularjs url query-parameters


    【解决方案1】:

    您需要将 $routeParams 服务注入控制器。只需将其作为参数添加到控制器函数即可。

    var app = angular.module('myModule');
    app.controller('homeController', function($scope, $http, $route, $routeParams) {
        $scope.debug = $routeParams.debug === 'true' ? true : false;
        console.log($scope.debug);
    }
    

    --- 更新---

    路径

    使用$location.path() === '/debug' 检查当前路径是否为“/debug”。您需要注入 $location 服务。

    var app = angular.module('myModule');
    app.controller('homeController', function($scope, $http, $route, $location) {
        $scope.debug = $location.path() === '/debug';
        console.log($scope.debug);
    }
    

    查询参数

    这将允许您检查是否存在键入“debug”且值为“true”的查询参数。

    http://localhost:8081/cgi/#/home?debug=true
    

     

    var app = angular.module('myModule');
    app.controller('homeController', function($scope, $http, $route, $location) {
        $scope.debug = $location.search().debug;
        console.log($scope.debug);
    }
    

    【讨论】:

    • console.log("$routeParams.debug); 上面给出了未定义。我如何访问调试作为查询参数 true 或 false?我应该使用 localhost:8081/cgi/#/debug/true 和 .when('/debug/true ', { ... }
    • 哦,等等。我误解了你想做什么。 Debug 不会作为参数传入,因为它没有在 app.config 中正确设置。如果你只想检查当前路径是否是 homeController 中的 /debug,你可以使用 $location 服务。
    • @SiddharthShah 更新。
    • 更新成功。谢谢,你能告诉我如果我想在网址下面添加或调用我该怎么做吗? localhost:8081/cgi/#/home?debug=true 或 localhost:8081/cgi/#home?debug
    • @naiveTechie 更新了我的答案
    猜你喜欢
    • 2016-07-06
    • 1970-01-01
    • 2017-08-07
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    相关资源
    最近更新 更多