【问题标题】:Angular - pass info from array from one controller to anotherAngular - 将数组中的信息从一个控制器传递到另一个控制器
【发布时间】:2016-04-05 17:44:30
【问题描述】:

我在尝试在控制器中传递服务时遇到了一点问题。

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

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

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

【问题讨论】:

标签: javascript angularjs service factory


【解决方案1】:

稍微改一下:

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()相同的方式声明它们

【讨论】:

    【解决方案2】:

    你应该这样做:

    服务是 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功能等我让你自己找。

    你可以从这里开始:)

    【讨论】:

      猜你喜欢
      • 2014-02-04
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      相关资源
      最近更新 更多