阅读(1986) (0)

AngularJS 定义参数

2017-07-19 17:12:20 更新

在作路由定义时,可以匹配一个规则,规则中可以定义路径中的某些部分作为参数之用,然后使用 $routeParams 服务获取到指定参数。比如 /#/book/test 中,     作为参数传入到 controller 中:

<div ng-view></div>


<script type="text/javascript">

angular.module('ngView', [],
  function($routeProvider){
    $routeProvider.when('/book/:title',
      {
        template: '{{ title }}',
        controller: function($scope, $routeParams){
          $scope.title = $routeParams.title;
        }
      }
    );
  }
);

</script>

访问: /#/book/test

不需要预定义模式,也可以像普通 GET 请求那样获取到相关参数:

angular.module('ngView', [],
  function($routeProvider){
    $routeProvider.when('/book',
      {
        template: '{{ title }}',
        controller: function($scope, $routeParams){
          $scope.title = $routeParams.title;
        }
      }
    );
  }
);

访问: /#/book?title=test