我試圖通信兩個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
有一個值。
創建一個小提琴。用直接函數替換數據庫代碼來模擬您的環境。 –