2014-04-04 80 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模板。