【问题标题】:Pass specific data from one controller to another将特定数据从一个控制器传递到另一个控制器
【发布时间】:2015-03-23 23:56:47
【问题描述】:

我有一个清单。我想要的是,当我单击 List 的一项时,应该打开一个新页面,其中显示仅与该 listItem 相关的数据。现在我正在使用锚标记和 .config 来传递这样的数据:

<ion-item ng-repeat="field in fields">
    <a href="#detail/{{field.firstName}}/{{field.personNo}}/{{field.street}}/{{field.city}}/{{field.postcode}}" id="a-item"> <div style="width:100%;height:100%" >    
         {{field.firstName}}<br>
         {{field.personNo}} </div></a> 
 </ion-item>

还有

.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
  when('/', {
    templateUrl: 'templates/mainpage.html'

  }).
  when('/detail/:name/:no/:street/:city/:postcode', {
    templateUrl: 'templates/details.html',
    controller: 'detailctrl'
})
}])

我认为这不是传递数据的有效方式。虽然我知道 .service 但我想不出一种方法来传递特定于所单击项目的数据。请提出更好的方法。谢谢

【问题讨论】:

    标签: angularjs ionic-framework


    【解决方案1】:

    您正在查看的是您确实希望使用服务(或工厂)的经典主细节模式。

    我将对您的代码进行的第一个更改是给主路由一个控制器,以及只传递 personNo 的详细路由。

    .config(['$routeProvider',function($routeProvider) {
        $routeProvider.
          when('/', {
            templateUrl: 'templates/mainpage.html',
            controller: 'mainctrl'
          }).
          when('/detail/:no', {
            templateUrl: 'templates/details.html',
            controller: 'detailctrl'
        })
    }])
    

    接下来,让我们通过具有两种方法的工厂设置“PeopleService”。一种是 GetPeople 方法,它获取数组中的所有人并通过 $http 解析承诺,然后将其存储在私有变量中。 GetPerson 方法通过 personNo 在该私有变量中查找人员。

    .factory('PeopleService',['$http',function($http){
        var people = [];
        return {
            GetPeople: function(){ 
                $http.get("path/to/resource").then(function(response){
                    people = response;
                    return response;
                });
            },
            GetPerson: function(personNo){
                for(i=0;i<people.length;i++){
                    if(people[i].personNo == personNo){
                        return people[i];
                    }
                }
            }
        }
    }]);
    

    接下来,在我们的 mainctrl 中,我们将要调用 GetPeople 函数。

    .controller("mainctrl",['PeopleService',function(PeopleService){
        PeopleService.GetPeople().then(function(people){
            $scope.people = people;
        });
    }]);
    

    最后,在我们的 detailsctrl 中,我们将从 $routeParams 中获取 personNo,并使用它从我们的服务中调用 GetPerson 方法。

    .controller("detailctrl",['$routeParams','PeopleService',function($routeParams,PeopleService){
        var personNo = $routeParams.no;
        $scope.person = PeopleService.GetPerson(personNo);
    }]);
    

    【讨论】:

    • 正是我想要的。
    • 如果用户深层链接到详细视图会发生什么?我相信它会抛出一个错误,因为 AJAX 请求从未发出过......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    相关资源
    最近更新 更多