【问题标题】:Ng-repeat using $scope from a different state?Ng-repeat 使用来自不同状态的 $scope?
【发布时间】:2016-02-11 23:44:56
【问题描述】:

我有两个视图,第一个(搜索)有一个按钮,单击该按钮会将项目添加到 $scope.results1,然后将用户带到 ng-repeat 所在的另一个视图(结果)。

当我单击按钮并出现结果页面时,仅显示“1”。但是,如果我直接在控制器中调用测试函数,我会被带到结果页面,并显示“1”和“2”。在这两种情况下,控制台日志都显示数组 results1 包含 2 个项目。

根据我的阅读,解决方案是实现工厂或服务,但我对 Ionic/angular 还很陌生,所以不太确定如何开始这样的实现,任何指针都将不胜感激!

搜索视图中的按钮:

<button class="button-full" id="find" ng-click="test();">Find</button>

搜索控制器:

 $scope.results1=[];
 $scope.results1.push(1);

 $scope.test = function(){
    $scope.results1.push(2);
    console.log("pushed 2");
    console.log($scope.results1);
    $state.go("tab.results");
  };

结果视图:

<ion-content ng-controller="SearchController">
    <body>
      <div id="results">
      <div class="list" id="search-items">
        <div ng-repeat="item in results1">
          {{item}}
        </div>
      </div>
    </div>
    </body>
</ion-content>

【问题讨论】:

    标签: angularjs ionic-framework angularjs-scope angularjs-ng-repeat


    【解决方案1】:

    你可以实现一个服务来保存这样的结果

    var mainApplicationModule = angular.module("yourAppName");
    
    mainApplicationModule.service('ResultService', function(){
        var results = [];
        this.add = function(data){    // to add data to results
            results.push(data);
        }
    
        this.getResults = function(){    // to get all results
            return(results);
        }
    }) 
    

    像这样将 ResultService 注入您的 SearchController,

    mainApplicationModule.controller('SearchController',['$scope','ResultService','$location', function($scope,ResultService,$location) {
    
        ResultService.add(1)            // Adds 1 to 'results' array in ResultService
        $scope.test = function() {
            ResultService.add(2);        // Adds 2 to Results array in ResultService
            $location.path("/results")  // replace with path to your results view
        }
        $scope.results1 = ResultService.getResults();  //  will have [1,2]
    }
    

    【讨论】:

      【解决方案2】:

      您可以在更改状态时传递数据,

      像这样配置状态:

      .state('tab.results', {
        url: '/yoururl',
        templateUrl: 'yourtemplate',
        controller: 'yourcontroller',
        params: {
            "results": ""
        }
      });
      

      然后使用:

      $state.go("tab.results",{"results": $scope.results1});
      

      在第二个控制器中注入 $stateParams 并获取值:

      $scope.results = $stateParams.results;
      

      【讨论】:

      • 我目前对两个视图都使用 SearchController,我应该为结果视图创建一个单独的控制器吗?
      • 如果您为多个视图使用相同的控制器,那么您需要一个服务来在它们之间共享数据。或者像我的例子一样制作多个控制器并改变状态
      猜你喜欢
      • 2013-06-25
      • 2014-10-11
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 2015-01-18
      • 1970-01-01
      相关资源
      最近更新 更多