【问题标题】:UI-Router, I am trying to pass id in the url, but I keep getting nothingUI-Router,我正在尝试在 url 中传递 id,但我一直一无所获
【发布时间】:2016-09-06 13:04:54
【问题描述】:

我正在尝试在 url 中传递 id,以便其他页面更具体地说是详细信息页面可以使用它,但我什么也没得到。 url 将转到正确的路线,但 id 没有被传入。我不知道我做错了什么。

这里是我的 app.js 文件:

$stateProvider.state('contact', {

    url: '/contact',

    templateUrl: 'templates/contact.html',
    controller: 'mainController'

});

$stateProvider.state('contact.detail', {

    url: '/detail/:id',

    templateUrl: 'templates/contact.detail.html',
    controller: 'detailController'
});

这是我的控制器文件:

myApp.controller('detailController', ['$scope', '$stateParams', 
  function ($scope, $stateParams) {

    'use strict';

    $scope.peoples = $scope.peoples[$stateParams.id];


}]);

这是我的联系文件:

<div class="container">
<div class="row">
    <div class="col-md-6">
        <table class="table table-striped">
            <thead>
                <th>First name</th>
                <th>Last name</th>
                <th>Age</th>
            </thead>
            <tbody>
                <tr ng-repeat="person in peoples">
                    <td><a ui-sref="contact.detail({id: person.id})">{{person.firstname}}</a></td>
                    <td>{{person.lastname}}</td>
                    <td>{{person.age}}</td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="col-md-6">
        <div ui-view></div>
    </div>
</div>

【问题讨论】:

  • peoples 数组到达详细信息控制器时是否有值? $scope.peoples ?尝试在详细信息控制器中将alert( $stateParams.id) 作为第一行。
  • 你确认没有任何东西被传递给$stateParams - 也许做一个console.log($stateParams) in your controller and call the url directly as in 'localhost:.../detail/foo`?,

标签: angularjs html angular-ui-router angular-ui state


【解决方案1】:

有一个working example

一件事是:

使用索引器搜索,例如$scope.peoples[someIdValue] 不会按 ID 而是按位置找到 (index)

第二点是:

不要重新分配具有新值的引用$scope.peoples(并丢失该引用)

所以,这应该是解决方法(使用 lodash 来找人)

.controller('detailController', ['$scope', '$stateParams', 
   function($scope, $stateParams) {

      //$scope.peoples = $scope.peoples[$stateParams.id];
      $scope.person = _.find($scope.peoples, {id: $stateParams.id});

  }])

检查action here中的所有内容

【讨论】:

    猜你喜欢
    • 2020-04-26
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多