Pew
Pew

Reputation: 3

AngularJS: one or many directives?

My problem: I have product object like this: {id: 1, category: 'Television', price: '$2000',...}, then I create product directive. User can buy a product by using product scope function buy(quantity). But I have many products, create scope with this function for every product might be waste of memory? Should I create additional directive, productBuyer has method: buy(product, quantity), then product directive require: '^productBuyer' will be put within it? Which design is better when application scales? Or is there any else way better?

More: I don't put buy to factory because product has to display error message if buy fail (for many reasons: out-of-date product, product-warehouse is empty, don't deliver to user's location...), this process method is passed to product directive.

Upvotes: 0

Views: 100

Answers (1)

New Dev
New Dev

Reputation: 49590

I would restrict the use of directives to self-contained and reusable bits of functionality. In your example, put common functionality in the directive, but keep functionality related to the broader app in the view's controller - not in the directive.

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

Finally, in your HTML you can do:

<div ng-controller="shoppingCtrl">
   <div ng-repeat="item in products" product="item" on-buy="buyProduct(item)"></div>
   <hr/>
</div>

Upvotes: 1

Related Questions