AngularJS:一个或多个指令?

时间:2014-10-30 02:42:12

标签: angularjs performance optimization angularjs-directive

我的问题:我有这样的产品对象:{id: 1, category: 'Television', price: '$2000',...},然后我创建了product指令。用户可以使用product范围函数buy(quantity)购买产品。但是我有很多产品,用这个功能创建范围,每个产品都可能浪费内存?我应该创建其他指令,productBuyer方法有:buy(product, quantity),那么product指令require: '^productBuyer'会被置于其中吗?当应用程序扩展时,哪种设计更好?或者还有其他更好的方法吗?

更多:我没有将buy置于工厂,因为如果购买失败,product必须显示错误消息(原因很多:产品过期,产品仓库为空,不要传递到用户的位置...),此流程方法将传递给product指令。

1 个答案:

答案 0 :(得分: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>