簡體   English   中英

無法在angularjs中將數據從服務發送到控制器

[英]Unable to send data from service to controller in angularjs

在我的小型購物應用程序中,我嘗試將添加到購物車的產品詳細信息發送給另一個控制器,然后將其顯示給其他控制器。 我使用了服務,但是在調試時返回空數組。 我有兩個控制器:productlistcontroller.js:

    app.controller("productListCtrl", function ($scope, $filter, productListActiveClass, productListPageCount, productListService) {
$scope.addProductToCart = function (product) {
            $scope.cartArr = addProduct(product.ProductId, product.name, product.price);
            productListService.save($scope.cartArr);
        }
})

checkoutcontroller.js:

app.controller("cartSummaryController", function ($scope, productListService) {
    $scope.cartData = productListService.getCartdata();
});

service.js

app.service("productListService", function ()
{
    var cartArray = [];
    this.save = function (cartArray) {
        this.cartArray = cartArray;
    }
    this.getCartdata = function () {
        return cartArray;
    }
})

我無法使用cartArray。 謝謝你的幫助。

除了Satpal描述的問題外,代碼中還有另一個問題:您在創建cartSummaryController時要求提供“ productListService.getCartdata()” 但是實際值將在以后設置(可能基於用戶輸入)。

因此,您要么需要向您的服務中添加一些發布機制,然后它就將數據更改通知其他人/訂閱者。 或者,您可以從.getCartdata()返回一個對象。 當您從保存中獲取數據時, 填充過去已經返回的對象。

編輯:添加了稍微修改的代碼以展示它如何工作:

 var app = angular.module("app",[]); app.controller("productListCtrl", function ($scope, productListService) { $scope.addProductToCart = function (product) { productListService.save($scope.data); } }); app.controller("cartSummaryController", function ($scope, productListService) { $scope.container = productListService.getCartdata(); }); app.service("productListService", function () { var container = {cartData: []}; this.save = function (name) { container.cartData.push(name); }; this.getCartdata = function () { return container; }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="app"> <div ng-controller="productListCtrl"> Product Controller - type text and click 'addToCart': <br/> <input type="text" ng-model="data" /> <input type="button" value="addToCart" ng-click="addProductToCart()"> </div> <div ng-controller="cartSummaryController"> CartData - updates automatically: <ul> <li ng-repeat="entry in container.cartData"> {{entry}} </li> </ul> </div> </body> 

這樣,您可以將container.cartArray綁定到發出請求的控制器中的html,並在每次調用save時對其進行更新。

問題在於,僅在加載控制器后才調用getCartdata方法,而在更改數據時才調用。 而是將指向服務功能的指針傳遞給控制器

更換:

$scope.cartData = productListService.getCartdata();

在:

$scope.cartData = productListService.getCartdata;

在您看來,您可以執行以下操作:

<div ng-repeat="item in cartData()">{{item}}</div>

這樣,您將獲得更新的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM