AngularJS多个单个绑定与一个大型绑定

时间:2014-04-04 09:14:51

标签: angularjs data-binding angularjs-ng-repeat

什么会更有效/更好的做法:将多个对象属性绑定到不同的范围属性,或将整个对象绑定到范围并访问模板中的属性。

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

单个对象绑定:

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 个答案:

答案 0 :(得分:1)

这取决于您的指令需要做什么。 我主要使用指令来定制输入;通常我有一个中心对象与&#39;模型&#39; (我可能发送到服务器的对象)可能很复杂,以及用于设置自定义输入的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模板。