2017-04-21 89 views
1

我试图通信两个controllers两个控制器之间在angularjs中进行通信1

var main = angular.module('starter', ["ionic", "ngCordova", "starter.services"]); 

cart-ctrl.js

main.controller('CartCtrl', 
    ["$scope", "global", 
    function($scope, global) { 
    $scope.$on("globalvar", function() { 
    //alert("from service cart: " + global.cart.items); 
    console.log("from service cart: " + global.cart.items); 
    $scope.carts = global.cart.items; 
    }); 
}]); 

menu-ctrl.js

main.controller('AppCtrl', 
    ["$scope", "$state", "global", 
    function($scope, $state, global) { 
    $scope.cart_click = function() { 
    global.updateCart(); 
    $state.go('app.cart'); 
    } 
}]); 

services.js

var service = angular.module("starter.services", []); 
service.factory("global", ["$rootScope", "database", 
    function($rootScope, database) { 
    var service = { 
    cart: { 
     items: [], 
     count: 0 
    }, 
    broadcastItem: function() { 
     $rootScope.$broadcast("globalvar"); 
    }, 
    updateCart: function() { 
     database.select_cart(function(p_cart) { 
     this.cart.items = p_cart; 
     alert("service cart: " + JSON.stringify(this.cart.items)); 
     }); 
     this.broadcastItem(); 
    } 
    }; 
    return service; 
}]); 

我想发生的事情是,当我点击选项卡(这触发了cart_click()),购物车清单将重新更新。然而没有价值被传入CartCtrl。我不知道这段代码有什么问题。当我通过database的值时,service.cart.items有一个值。

+0

创建一个小提琴。用直接函数替换数据库代码来模拟您的环境。 –

回答

0

我想你应该叫this.broadcastItem();您的数据库调用的回调中。回调里面的this的上下文实际上并不是相同的服务。更新您的代码为

updateCart: function() { 
    var self = this; 
    database.select_cart(function(p_cart) { 
    self.cart.items = p_cart; 
    self.broadcastItem(); 
    alert("service cart: " + JSON.stringify(self.cart.items)); 
    }); 
} 
相关问题