2014-04-04 39 views
0

什么会更有效率/更好的做法:将多个对象属性绑定到不同的作用域属性或将整个对象绑定到作用域并访问模板中的属性。AngularJS多个单个绑定vs一个大型绑定

以下是这两种情况的一些例子:

单对象绑定:

directive('info', [function(){ 
    return { 
     scope: { 
      object: "=" 
     }, 
     restrict: 'E', 
     template: '<div>\ 
      <div>{{ object.something }}</div>\ 
      <div>{{ object.something2 }}</div>\ 
      <div>{{ object.something3 }}</div>\ 
      <div>{{ object.something4 }}</div>\ 
      <div>{{ object.something5 }}</div>\ 
     </div>', 
     replace: true 
    }; 
}]); 

<info ng-repeat="info in infoArray" object="info"></info> 

多个绑定:

directive('info', [function(){ 
    return { 
     scope: { 
      something: "=", 
      something2: "@", 
      something3: "@", 
      something4: "=", 
      something5: "@", 
     }, 
     restrict: 'E', 
     template: '<div>\ 
      <div>{{ something }}</div>\ 
      <div>{{ something2 }}</div>\ 
      <div>{{ something3 }}</div>\ 
      <div>{{ something4 }}</div>\ 
      <div>{{ something5 }}</div>\ 
     </div>', 
     replace: true 
    }; 
}]); 

<info 
    ng-repeat="info in infoArray" 
    something="info.something" 
    something2="info.something2" 
    something3="info.something3" 
    something4="info.something4" 
    something5="info.something5"> 
</info> 

回答

1

这取决于你的指令需要做什么。 我主要使用自定义输入指令;通常我有一个中心对象,其中包含可能很复杂的“模型”(我可能发送到服务器的对象)以及用于设置自定义输入的UI选项的其他属性。 例如:简单的日期选择器可以具有这样的结构:

directive('datepick', [function(){ 
    return { 
    scope: { 
     model  : "=ngDatepicker", 
     format : "@format", 
     readonly : "@ngRead" 
    }, 
    restrict: 'E', 
    /* etc. ... */ 

并且这些可能是这样的:

$scope.model = { 
    day : '', 
    month : '', 
    year : '', 
    wholedate : '' 
}; 
$scope.format = 'YYYY-MM-DD'; 
$scope.read = false; 

和HTML可能是这样的:

<datepick ng-datepicker="model" format="format" read="read"></datepick> 

在你发布的例子(我假设它只是为了显示信息,而不处理它),我会用单个对象绑定去;这样,如果infoArray内部的对象更改结构,则不需要更改所有的html模板。