角 - 从一个控制器传递到另一个阵列从信息 [英] Angular - pass info from array from one controller to another

查看:105
本文介绍了角 - 从一个控制器传递到另一个阵列从信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题试图控制器内传递服务。

我试图做的是一个购物车,我有一个项目列表,当我打了一个按钮,这些项目被添加到购物车,然后我想列出一个单独的页面购物车中的那些项目使用一个单独的控制器,所以我试图用一个工厂的车,但我不知道你是否能控制器中设置一个工厂对象。

下面是我的code,希望你能指出我在正确的方向。

  VAR应用= angular.module(商店,[]);app.factory('的DataService',函数(){
VAR车= [];
VAR套=功能(数据){
    购物车=数据;
}
VAR的get =功能(){
    返回购物车;
}
});app.controller(catalogController功能($范围,$ HTTP){
$ scope.bookStore = {
    选择:{},
    书:空
};
$ scope.cart = [];
$ http.get(JSON / books.json)
    .success(功能(数据){
        的console.log(数据);
        $ scope.bookStore.books =数据;
    })
    .error(功能(错误){    });$ scope.addToCart =功能(书){
    VAR发现= FALSE;
    $ scope.cart.forEach(函数(项目){
        如果(item.id === book.id){
            item.quantity ++;
            发现= TRUE;
        }
    });
    如果(!找到){
        $ scope.cart.push(angular.extend({
            数量:1
        },书籍));
    }
};$ scope.removeFromCart =功能(项目){
    VAR指数= $ scope.cart.indexOf(项目);
    $ scope.cart.splice(指数,1);
};$ scope.getCartPrice =功能(){
    无功总= 0;
    $ scope.cart.forEach(功能(产品){
        总+ = product.price * product.quantity;
    });
    总回报;
};
});app.controller(checkoutController功能($范围的DataService){
$ scope.cart = DataService的;
});


解决方案

您应该做这样的事情:

一个服务是角JS一个单身,这意味着你只需要这个类的一个实例在你的应用程序。

  VAR应用= angular.module(商店,[]);    app.factory('的DataService',函数($ HTTP){// usualy您服务是打电话给你的API之一(不是你的控制器)
    VAR车= NULL; //车阵在类私有的实例设置    返回{//此处声明的所有你想从外部调用的函​​数(你的控制器)
             设置:功能(数据){
                 购物车=数据;
             },
              得到:函数(){
               返回购物车;
             },
             getFromAPI =功能(){//将code你在你的控制器有应放在这里
                 返回$ http.get(JSON / books.json)
                       .success(功能(数据){
                           的console.log(数据);
                        购物车=数据; //现在你设置你cart变量
                       })
                      .error(功能(错误){                   });
             },
        });

然后在您的控制器:

  app.controller(catalogController功能($范围的DataService){//包括你的服务作为一个依赖
$ scope.bookStore = {
    选择:{},
    书:空
};
$ scope.cartInCatalogController = DataService.get(); //它将设置的车是在你的服务,你的控制器的范围值
如果(!$ scope.cartInCatalogController){//如果是空,因此调用API
      DataService.getFromAPI()//这个函数返回一个承诺
        .success(功能(数据){//这样称呼成功函数
             $ scope.cartInCatalogController =数据;
         })
        .error(功能(错误){
           //做一些事情在这里,如果你想
      });
});

您可以做同样在其他的控制器。
关于addToCard功能和其他的东西,我让你自己找吧。

您可以从这里开始:)

I'm having a little problem trying to pass a service within controllers.

What I'm trying to do is a shopping cart, I have a list of items and when I hit a button, those items get added to the cart, then I want to list those items in the cart in a separate page using a separate controller, so I'm trying to use a factory for the cart, but I don't know if you can set a factory object within a controller.

Here's my code, hope you can point me in the right direction.

var app = angular.module("Shop", []);

app.factory('DataService', function () {
var cart = [];
var set = function (data) {
    cart = data;
}
var get = function () {
    return cart;
}
});

app.controller("catalogController", function ($scope, $http) {
$scope.bookStore = {
    selected: {},
    books: null
};
$scope.cart = [];
$http.get("json/books.json")
    .success(function (data) {
        console.log(data);
        $scope.bookStore.books = data;
    })
    .error(function (err) {

    });

$scope.addToCart = function (book) {
    var found = false;
    $scope.cart.forEach(function (item) {
        if (item.id === book.id) {
            item.quantity++;
            found = true;
        }
    });
    if (!found) {
        $scope.cart.push(angular.extend({
            quantity: 1
        }, book));
    }
};

$scope.removeFromCart = function (item) {
    var index = $scope.cart.indexOf(item);
    $scope.cart.splice(index, 1);
};

$scope.getCartPrice = function () {
    var total = 0;
    $scope.cart.forEach(function (product) {
        total += product.price * product.quantity;
    });
    return total;
};
});

app.controller("checkoutController", function ($scope, DataService) {
$scope.cart = DataService;
});

解决方案

You should do something like this:

A service is a singleton in angular js, that's mean you only have one instance of this class in your app.

var app = angular.module("Shop", []);

    app.factory('DataService', function ($http) { // usualy your service is the one which call your API (not your controller)
    var cart = null; // the cart array is set in the instance of the class as private

    return{ // here you declare all the functions you want to call from outside (your controllers)
             set : function (data) {
                 cart = data;
             },
              get: function(){
               return cart;
             },
             getFromAPI = function () { // the code you have in your controller should goes here
                 return $http.get("json/books.json")
                       .success(function (data) {
                           console.log(data);
                        cart = data; //now you set you cart variable
                       })
                      .error(function (err) {

                   });
             }, 
        });

Then in your controllers:

app.controller("catalogController", function ($scope, DataService) { // include your service as a dependency
$scope.bookStore = {
    selected: {},
    books: null
};
$scope.cartInCatalogController = DataService.get(); // it will set the value of cart that's in your service to your controller's scope
if(!$scope.cartInCatalogController) {// if it's null so call the API
      DataService.getFromAPI()// this function should return a promise
        .success(function(data){// so call the success function
             $scope.cartInCatalogController = data;
         })
        .error(function(error){
           // do something here if you want
      });
});

You can do the same in your other controller. About the addToCard function and other stuff I let you find it by yourself.

You can start from here :)

这篇关于角 - 从一个控制器传递到另一个阵列从信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆