我是angularjs的新手。我在某處找到了下面的例子,它的工作正常。但是,我不明白定製指令控制器中的數據如何與工廠數據同步。下面是代碼:定製指令控制器數據與工廠數據同步
angular.module("cart",[]).factory("cart", function(){
var cartData = [];
return{
addProduct:function(id, name, price){
cartData.push({count:1, id:id, price:price, name:name})
},
getProduct: function(){
return cartData;
}
};
}).directive("cartSummary", function(cart){
return{
restrict: "E",
template:"cartSummary.html",
controller: function($scope){
var cartData = cart.getProduct();
$scope.totalPrice = function(){
var total = 0;
for(var i=0; i<=cartData.length; i++){
total+= (cartData[i].price * cartData[i] * count);
}
}
}
}
});
,並在另一模塊,我有以下的代碼來更新cartData:
angular.module("store", ["cart"]).controller("storeCtrl", function($scope, cart){
/*some logic here*/
$scope.addToCart = function(){
cart.addProduct(product.id, product.name, product.price);
}
});
這裏是視圖:
<html ng-app="store">
<body ng-controller="storeCtrl">
<!--some html-->
<cart-summary/>
<!--some html-->
<button ng-click="addToCart(item)">Add To Cart</button>
</body>
</html>
指令的模板:
<div class="navbar-text">
{{totalPrice()}}
</div>
我瞭解每次用戶點擊「添加到購物車」按鈕時,工廠中的cartData都會得到更新,但我沒有明白工廠中cartData的事實總是與定製指導控制器中的數據同步。每次函數$ scope.totalprice()如何被調用?
有人可以向我解釋這個嗎?非常感謝!
OMG,多數民衆贊成在正確的!非常感謝! – 2014-08-29 01:24:38
現在我很困惑模板視圖中的totalPrice()每次如何被調用。你能解釋一下嗎?非常感謝你 – 2014-08-29 16:48:29
實際上,它確實會產生內存泄漏,因爲它的摘要循環中的角度比較它的變量值和它們在此之前的摘要循環中的先前值。 得到這個的簡單方法是角度不知道函數是否改變了結果,所以在每個摘要循環中角將會一次又一次地執行它。在插值{{}}內調用函數被認爲是不好的做法,特別是重邏輯函數。相反,預先計算結果並將其綁定到範圍的屬性 – HeberLZ 2014-08-30 06:20:44