欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

AngularJS通过路由模块ui-sref指令跳转页面传参方法

程序员文章站 2022-04-15 22:13:10
...
路由router.js
'use strict';

angular.module('app').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $stateProvider.state('main', {
    url: '/main',
    templateUrl: 'view/main.html',
    controller: 'mainCtrl'
  }).state('position', {
    url: '/position/:id',                  //这里需要传入一个id的参数放在url后面传递过去
    templateUrl: 'view/position.html',
    controller: 'positionCtrl'
  });
  $urlRouterProvider.otherwise('main');
}])

控制器controller

'use strict'angular.module('app').controller('mainCtrl',['$scope',function($scope){
$scope.list = [{
id:'1', //将这个id写到页面上
name:'销售',
imgSrc:'image/company-3.png',
companyName: '千度',
city: '上海',
industry: '互联网',
time: '2016-06-01 11:05'
},{
id:'2',
name:'WEB前端',
imgSrc:'image/company-1.png',
companyName: '慕课网',
city: '北京',
industry: '互联网',
time: '2016-06-01 01:05'
}];
}]);

html模板

<ul class="bg-w position-list">//通过ui-sref="position({id:item.id})"的方式将参数传递过去    
            <li ui-sref="position({id:item.id})" class="item" ng-repeat="item in data">
        <img class="f-l logo" ng-src="{{item.imgSrc}}" alt="">
        <h3 class="title" ng-bind="item.name"></h3>
        <p class="text" ng-bind="item.companyName+'
                ['+item.city+']'+' '+item.industry"></p>
        <p class="text" ng-bind="item.time"></p>
    </li></ul>

获取路由上参数:
注入$state服务,$state服务下有个$state.params属性,这个$state.params属性是个json对象,这个json对象所包含的数据就是我们前面传入的参数。

'use strict';
angular.module('app').controller('positionCtrl',['$q','$http','$state','$scope',function ($q,$http,$state,$scope) {

              //获取id的参数,并用$http请求对应的数据
              $http.get('/data/position?id='+$state.params.id).success(fn1).error(fn2);

}]);

AngularJS跨页面传参方式小结:
①在路由中声明url: ‘/url/:参数’;
②获取数据通过ui-sref=”url({id:item.id})”的方式将参数挂载到url后面;
③在控制器中注入$state服务,利用\$state.params属性获取传过来的参数。

AngularJS通过路由模块ui-sref指令跳转页面传参方法

以上就是AngularJS通过路由模块ui-sref指令跳转页面传参方法 的详细内容,更多请关注其它相关文章!