从函数调用控制器并将其传递给URL编码的参数

时间:2016-02-26 10:05:51

标签: javascript angularjs angularjs-routing

我正在为Rest服务开发CRUD接口。目前,我可以设法获得系统中的团队列表。

我喜欢的是显示点击显示链接的详细信息。当前单击该链接会调用一个函数(尚未实现),该函数应该将详细信息部分加载到ng-view中。该函数应将参数传递给ViewTeamController,随后将调用Rest服务并将结果提供给$scope变量。

我不确定如何使用ViewTeamController函数中的URL编码参数调用showTeam()。我还想知道如何阅读ViewTeamController

中的URL编码参数

提前致谢。

<!doctype html>
<html>

<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular-route.min.js"></script>

    <script>
        var teamApp = angular.module("teamApp", ['ngRoute']);

        teamApp.controller('teamController', function($scope, $http) {

            $http
                    .get('/teams')
                    .success(function(response) {
                        $scope.teams = response;
                    }
                    );
        });

        mainApp.config(['$routeProvider', function($routeProvider) {
            $routeProvider.

            when('/addTeam', {
                templateUrl: 'addTeam.htm',
                controller: 'AddTeamController'
            }).

            when('/viewTeam', {
                templateUrl: 'viewTeam.htm',
                controller: 'ViewTeamController'
            }).

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

        mainApp.controller('AddTeamController', function($scope) {

        });

        mainApp.controller('ViewTeamController', function($scope) {

        });

    </script>
</head>

<body>

<div ng-app = "teamApp" ng-controller="teamController">

    <a ng-click="newTeam()">new</a>

    <div ng-repeat="team in teams" >
        Name: {{team.name}}
        <br />
        Description: {{team.description}}
        <br />
        <a ng-click="showTeam(team.id)">show</a>
    </div>

    <div ng-view></div>

    <script type = "text/ng-template" id = "addTeam.htm">
        <h2> Add Team </h2>
        To be implemented later.
    </script>

    <script type = "text/ng-template" id = "viewTeam.htm">
        Name: {{team.name}}
        Description: {{team.description}}
    </script>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的控制器功能可以通过AngularJS $routeParams服务访问路由参数,如下所示:

 mainApp.controller('ViewTeamController', function($scope, $routeParams) {
              $scope.param = $routeParams.param;  // will hold your encoded params
        });

考虑到您在URL中传递了类似的参数,

/viewTeam/23535t4645645g4t4

现在,您的$scope.param将保留23535t4645645g4t4