0

What would be more efficient/a better practise: binding multiple object properties to different scope properties or binding the whole object to the scope and accessing the properties in the template.

Here are some examples of both scenarios:

Single object binding:

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>

Multiple bindings:

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 Answer 1

1

It depends on what your directive needs to do. I use directives mostly for custom inputs; usually I have a central object with the 'model' (an object that I potentially send to the server) that can be complex, and other attributes used to set UI options of the custom input. For example: a simple datepicker could have a structure like this:

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

and these could be like:

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

and the HTML could be like:

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

In the example you posted (I'm assuming it's only to display info, without manipulating it) I would go with the single object binding; that way if the objects inside infoArray change structure you don't need to change all the html templates.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.