Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

AngularJS directive two way binding for a configurable number of variables


When creating a directive, while defining isolate scope with two way binding using = is there any way that I can bind an array of scope variables. ie. if in my controller I have objects defined like $scope.one, $scope.two etc. and there can be any number of those - I want the directive to be able to handle a configurable number of them. How could I do that?

I can't do this, since another controller that uses the directive may have ten, so I want it to be flexible:

.directive("example", function () {
    return {
        scope: {
          one: "=",
          two: "=",
          three: "="
        },
    ...

Solution

  • Off course it is:

    .directive('example', function() {
       return {
         scope: {
           config: '='
         },
         link: function(scope) {
           var firstOption = scope.config[0];
           var secondOption = scope.config[1];
           //...
         }
       }
    }
    

    The array options would have to be stored at a fixed index, so it would be less readable than passing a config object

    .directive('example', function() {
           return {
             scope: {
               config: '='
             },
             link: function(scope) {
               var firstOption = scope.config.firstOption;
               var secondOption = scope.config.secondOption;
               //...
             }
           }
        }