如何在控制器之间传输数据 [英] How to transfer data between controllers

查看:23
本文介绍了如何在控制器之间传输数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在控制器之间传输数据.

所以这是我第一个使用 http- 加载页面时首先获取数据的控制器

function GetController($scope, $http) {$http.defaults.useXDomain = true;$http({方法:'POST',网址:serviceUrl + '/GetProductsByCategoryOrName',标题:{授权":apiKey},数据:{查询":杂货",categoryId":976759",pageIndex":0,sortDirection":asc"}}).then(函数successCallback(响应){$scope.products = response.data;}).then(function errorCallback(error) {})}

视图看起来像 -

 

<div class="mdl-cell" ng-repeat="product in products"><img src="{{product.largeImage}}"/><div class="mdl-card__title"><h6 class="mdl-card__title-text">{{product.name}}</h6>

现在我需要用相同的请求但不同的参数重新绑定这个 HTML.所以我为这个工作创建了另一个控制器-

function searchProductsController($scope, $http) {$http.defaults.useXDomain = true;$scope.searchText = "";$scope.submit = 函数 () {$http({方法:'POST',网址:serviceUrl + '/GetProductsByCategoryOrName',标题:{授权":apiKey},数据:{查询":$scope.searchText,categoryId":976759",pageIndex":0,sortDirection":asc"}}).then(函数successCallback(响应){$scope.products = response.data;//如何将其与 GetController 的 $scope.products 绑定?}).then(function errorCallback(error) {});}};

需要什么-

我想将 searchProductsController$scope.products 绑定到 GetController's $scope.products 以便它呈现在视图中.

我目前不知道如何做到这一点,因为我对 angular 很陌生.但是,我已经尝试创建用于传输目的的服务,但不知道如何将其与它集成.

编辑-

我已经按照@Varkal 建议使用服务编辑了控制器方法,但仍然无法解决问题.

var app = angular.module("productsApp", []).service("serviceProvider", function ($http) {this.getDatas = 函数 getDatas(data) {返回 $http({方法:'POST',网址:serviceUrl + '/GetProductsByCategoryOrName',标题:{授权":apiKey},数据:数据})}返回这个});函数 GetController($scope, serviceProvider) {var data = { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };serviceProvider.getDatas(data).then(function (response) {$scope.products = response.data.data;});}功能 searchProductsController($scope, serviceProvider) {var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };$scope.submit = 函数 () {serviceProvider.getDatas(data).then(function (response) {控制台日志(响应.数据.数据);$scope.products = response.data.data;});}};

解决方案

当你需要在控制器之间共享东西时,这些东西应该放在 服务

例如:

angular.service("datasService", function ($http) {this.getDatas = 函数 getDatas() {返回 $http({方法:'POST',网址:serviceUrl + '/GetProductsByCategoryOrName',标题:{授权":apiKey},数据:{查询":杂货",categoryId":976759",pageIndex":0,sortDirection":asc"}})}返回这个});

在你的控制器中:

function GetController($scope, datasService) {datasService.getDatas().then(function(){$scope.products = response.data}}

这是一个非常简单的例子:你也可以将数据存储在服务中,所以只调用一次 $http,并添加一个方法来刷新产品列表

这是在控制器之间共享数据最Angular-ly"的方式,但您也可以使用 localStorage (ngStorage可以在这里帮助你)

I am trying to transfer data between controllers.

So this is my first controller that fetches data first when page loads using http-

function GetController($scope, $http) {
    $http.defaults.useXDomain = true;
    $http({
        method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
            'Authorization': apiKey
        },
        data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
    }).then(function successCallback(response) {
        $scope.products = response.data;
    }).then(function errorCallback(error) {
    })
}

the view looks like-

 <div  ng-controller="GetController">
            <div class="mdl-cell" ng-repeat="product in products">
                 <img src="{{product.largeImage}}" />
                  <div class="mdl-card__title">
                    <h6 class="mdl-card__title-text">{{product.name}}</h6>
                </div>
            </div>
        </div>
    </div>

Where now my need is to rebind this HTML with the same request but different parameters. So I created another controller for this job-

function searchProductsController($scope, $http) {
    $http.defaults.useXDomain = true;
    $scope.searchText = "";
    $scope.submit = function () {
        $http({
            method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
                'Authorization': apiKey
            },
            data: { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
        }).then(function successCallback(response) {
            $scope.products = response.data; //how to bind this with GetController's $scope.products??
        }).then(function errorCallback(error) {
        });
    }
};

What is needed-

I want to bind $scope.products of searchProductsController to GetController's $scope.products so that it renders in view.

I don't have any idea how to do this at the moment as I am very new to angular. However, I've given a try to create service for transferring purpose but don't really have idea how to integrate it with it.

Edit-

I've edited controller methods as @Varkal suggested using service, Still couldn't get the problem resolved.

var app = angular.module("productsApp", [])
    .service("serviceProvider", function ($http) {
        this.getDatas = function getDatas(data) {
            return $http({
                method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
                    'Authorization': apiKey
                },
                data: data
            })
        }
        return this
    });

function GetController($scope, serviceProvider) {
    var data = { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };
    serviceProvider.getDatas(data).then(function (response) {
        $scope.products = response.data.data;
    });
}

function searchProductsController($scope, serviceProvider) {
    var data = { "query": $scope.searchText, "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" };

    $scope.submit = function () {
        serviceProvider.getDatas(data).then(function (response) {
            console.log(response.data.data);
            $scope.products = response.data.data;
        });
    }
};

解决方案

When you need to share things betweens controller, those things should be in a service

For example :

angular.service("datasService", function ($http) {
  this.getDatas = function getDatas() {
    return $http({
      method: 'POST', url: serviceUrl + '/GetProductsByCategoryOrName', headers: {
        'Authorization': apiKey
      },
      data: { "query": "grocery", "categoryId": "976759", "pageIndex": 0, "sortDirection": "asc" }
    })
  }
  return this
});

And in your controller :

function GetController($scope, datasService) {
  datasService.getDatas().then(function(){
    $scope.products = response.data
  }
}

This is a very simple example : you can also store your datas in the service, so call $http only once, and add a method to refresh the product list

This is the most "Angular-ly" way of share datas between controllers, but you can also use localStorage (ngStorage can help you here)

这篇关于如何在控制器之间传输数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆