角度-将数组中的信息从一个控制器传递到另一个控制器

Angular - pass info from array from one controller to another

本文关键字:控制器 一个 另一个 数组 信息 角度      更新时间:2024-01-04

我在控制器内传递服务时遇到了一个小问题。

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

这是我的代码,希望你能给我指明正确的方向。

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;
});

将内容更改为类似的内容

app.factory('DataService', function () {
    var cart = [];
    return {
        set: function (data) {
            cart = data;
        },
        get: function () {
            return cart;
        },
        add: function (item) {
            cart.push(item);
        }
     }
});
...
app.controller("checkoutController", function ($scope, DataService) {
    $scope.cart = DataService.get();
});

然后将$http.get方法和其他控制器中卡上的所有操作移动到工厂中的功能,并以与上述Dataservice.get() 相同的方式声明它们

您应该这样做:

服务是angular js中的单例,这意味着你的应用程序中只有一个此类的实例。

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) {
                   });
             }, 
        });

然后在您的控制器中:

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
      });
});

您可以在另一个控制器中执行相同操作。关于addToCard函数和其他东西,我让你自己找到它。

您可以从这里开始:)