我會限制使用指令來自包含和可重用的功能位。在您的示例中,將常用功能放入指令中,但在視圖的控制器中保留與更廣泛的應用程序相關的功能 - 而不是指令中的功能。
app.js
angular.module("myApp", []).
.controller("shoppingCtrl", function($scope, productSvc){
productSvc.getProducts()
.then(function(products){
$scope.products = products;
});
$scope.buyProduct = function(product){
productSvc.buy(product)
.then(function(){ /* do something */ });
}
})
.directive("product", function(){
return {
restrict: "EA",
scope: {
product: "=",
onBuy: "&"
},
templateUrl: "productDirective.html",
controller: function($scope){
$scope.clickOnBuy = function(){
$scope.onBuy();
}
}
};
});
productDirective.html
<div>
<div>{{product.title}}</div>
<div>{{product.price}}</div>
<button ng-click="clickOnBuy()">Buy</button>
</div>
的index.html
最後,在你的HTML你可以這樣做:
<div ng-controller="shoppingCtrl">
<div ng-repeat="item in products" product="item" on-buy="buyProduct(item)"></div>
<hr/>
</div>
您打算在單個頁面上顯示100K-1M產品嗎?沒有?然後,不要再擔心浪費內存。 – 2014-10-30 03:06:48
@NewDev:感謝您的評論。關於設計模式,使用一個指令更好? – Pew 2014-10-30 03:17:10
我不一定認爲使用「購買」它所代表的產品的指令是一個好主意。指令是自包含和可重用的功能位。他們可以連接到服務,但是像購買產品一樣,您的應用很可能會涉及(例如購物車,結賬等)。你肯定可以在每個指令上附加一個「購買」按鈕,但我會將購買功能放在控制器上。 – 2014-10-30 03:29:36