Michał Sałaban Michał Sałaban - 3 months ago 8
AngularJS Question

Passing variable to a directive and DRY?

I have some piece of code (not mine) which contains a directive with declared

scope
mapping. My wish is to use the directive in other place and pass additional variables which will be used within the template.

The variable I want to pass is
theVar
.

The only solution I found out to be working looks nightmarish:



(function(angular) {
'use strict';

angular.module('theFoo', [])

.controller('Controller', ['$scope', function($scope) {
$scope.theVar = true;
}])

.directive('aDirective', function() {
return {
scope: {
'someVarThatWasHereBefore': '=',
'theVar': '='
},
template: '<p ng-show="theVar">You have successfully passed a boolean value!</p>'
};
});

})(window.angular);

<body ng-app="theFoo">
<div ng-controller="Controller">
<a-directive data-the-var="theVar"></a-directive>
</div>
</body>





Is there any way to do it without repeating the name of my variable four times within the
scope
and the HTML element?

Answer

That code looks fine. As for repeating the name of the variable four times - that is how angular works to define directives, pass data to them, and use the data in the template.

It is not against DRY principles to define and pass variables around. DRY is more about not rewriting blocks of logic.

To be clear on naming of variables - the variable you pass into the directive does not need to match its name in the directive scope.

(function(angular) {
  'use strict';

  angular.module('theFoo', [])

  .controller('Controller', ['$scope', function($scope) {
    $scope.myVar = true;
  }])

  .directive('aDirective', function() {
    return {
      scope: {
        'someVarThatWasHereBefore': '=',
        'theVar': '='
      },
      template: '<p ng-show="theVar">You have successfully passed a boolean value!</p>'
    };
  });

})(window.angular);
<body ng-app="theFoo">
  <div ng-controller="Controller">
    <a-directive data-the-var="myVar"></a-directive>
  </div>
</body>