【问题标题】:Angular 1 (Ionic): Passing parameters with JSON dataAngular 1 (Ionic):使用 JSON 数据传递参数
【发布时间】:2016-08-25 15:13:23
【问题描述】:

我在这里使用 Ionic 框架,尝试通过单击将数据从一个模板传递到另一个模板。数据通过服务加载,使用 $http.get;两个模板(或视图)都在'MainController'下,所以我很困惑为什么数据不会通过? 在我使用 JSON 请求提取数据并将其放入服务之前,它工作得非常好。

我想我可能需要定义参数什么的?

看起来有点像:

服务

angular.module('myApp.services', [])
  .factory('exampleService', ['$http', function($http){
    return{
      get: function(callback){
          $http.get('http://json...').success(function(data) {
          // prepare data here
          callback(data);
        });
      }
    };
  }]);

控制器

.controller('MainController', function($scope, $http, exampleService) {

styleService.get(function (data) {
       $scope.styles = data;
      });
...

});

模板。 1

<ul class="list">
      <a class="..." collection-repeat="style in styles track by style.id" ng-click="styles.label = style.style" href="#/...">
        <h2 class="selector">{{style.id}}</h2>
            <i class="icon ion-ios-arrow-forward"></i>
        </a>
    </ul>

模板。 2

<h2>{{styles.label}}</h2>

(出于显而易见的原因,我省略了一些代码,但是除了传递这个选定的选项之外,它所有的功能都很好。)

谢谢!

【问题讨论】:

  • 你确定http请求成功了吗?你那里没有错误处理
  • 是的,列表已完全呈现。
  • “数据不会通过”是什么意思?
  • 你应该在$scope.styles = data;之后添加$scope.$apply();,并且在http请求失败时也调用回调
  • 用户单击列表中的一个项目,它应该打印到下一个视图(通过 ng-model="styles.label = style.style),但是这不会打印。

标签: angularjs ionic-framework


【解决方案1】:

我只需要将 $root. 附加到需要广播的 $scope. 上(这也适用于两个控制器,对于为此苦苦挣扎的人来说: ))

【讨论】:

    【解决方案2】:

    我担心你的控制器中的 styleService 是什么,工厂方法包含 exampleService。请检查一下。

    我的常见做法是通过在 factory 方法中声明和使用 variables 在模板或视图之间传递数据,如下所示

    angular.module('myApp').factory('AppData', function () {
        var connectionurl = 'http://localhost/api/...;
        var someobject;
        return
        {
        // the left argument can be of your choice where as the right side will be the name as you have declared above
        connectionurl:connectionurl,
        someobject:someobject,
        }
        });
    
    
    angular.module('myApp').controller('MainSampleController',
    function ($scope, $http, AppData) {
    
    // use the AppData variables for binding to 
        $scope.connectionurl= AppData.connectionurl;
        AppData.someobject= $scope.JsonObject;
    
    });
    
    angular.module('myApp').controller('AnotherSampleController',
    function ($scope, $http, AppData) {
    
        $scope.JsonObject=AppData.someobject;
    
    });
    

    【讨论】:

      猜你喜欢
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      相关资源
      最近更新 更多