Angular.js UI-Router如何将变量传递给状态URL?

14

我正在尝试像以下这样向angular.js ui-router中的状态传递参数:

.state('details', {
    url: '/details/:index',
    templateUrl: 'views/details.html'
})

该索引正在通过ng-repeat索引传递

 <div ng-repeat="program in programs">
            <h2>{{program.name}}</h2>

            <p>{{program.description || "No Description"}}</p>

            <p><a ui-sref="details({index: $index})">View details »</a></p>
 </div>

我的问题是如何在details.html中读取通过URL传递的索引值?

1个回答

12

在你的控制器中注入$stateParams

示例

var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){

  // For any unmatched url, send to /route1
  $urlRouterProvider.otherwise("/route1/2")

  $stateProvider
    .state('route1', {
        url: "/route1/:index",
        templateUrl: "route1.html",
        controller: function($stateParams, $scope) {
            $scope.index = $stateParams.index 
        }
    })
    .state('route2', {
        url: "/route2",
        templateUrl: "route2.html"
    })
});

1
非常感谢 @matys84pl,看起来正是我一直在寻找的。 - Fouad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接