2014-10-30 84 views
0

我的问题:我有这样的产品对象:{id: 1, category: 'Television', price: '$2000',...},然后我创建product指令。用户可以通过使用product示波器功能buy(quantity)购买产品。但是我有很多产品,用这个功能创造范围对于每一件产品都可能是浪费内存?我应该创建额外的指令,productBuyer有方法:buy(product, quantity),然后product指令require: '^productBuyer'将被放在里面吗?应用程序扩展时哪种设计更好?或者还有其他更好的方法吗?AngularJS:一个或多个指令?

更多:我不把buy出厂,因为product必须显示错误消息,如果购买失败(很多原因:过时的产品,产品仓库是空的,不交付给用户的位置。 ..),这个处理方法被传递给product指令。

+0

您打算在单个页面上显示100K-1M产品吗?没有?然后,不要再担心浪费内存。 – 2014-10-30 03:06:48

+0

@NewDev:感谢您的评论。关于设计模式,使用一个指令更好? – Pew 2014-10-30 03:17:10

+0

我不一定认为使用“购买”它所代表的产品的指令是一个好主意。指令是自包含和可重用的功能位。他们可以连接到服务,但是像购买产品一样,您的应用很可能会涉及(例如购物车,结账等)。你肯定可以在每个指令上附加一个“购买”按钮,但我会将购买功能放在控制器上。 – 2014-10-30 03:29:36

回答

1

我会限制使用指令来自包含和可重用的功能位。在您的示例中,将常用功能放入指令中,但在视图的控制器中保留与更广泛的应用程序相关的功能 - 而不是指令中的功能。

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> 
+0

酷!现在我还有其他问题。如果我没有通过'onBuy'功能,我不想显示购买按钮。我怎样才能做到这一点? – Pew 2014-10-30 08:25:07

+0

将'ng-if =“onBuy”'加入购买按钮。如果定义了“onBuy”,则会显示按钮 – 2014-10-30 08:28:34

+0

尼斯。非常感谢你! – Pew 2014-10-30 08:30:25