kenshin9
kenshin9

Reputation: 2375

AngularJS - $compile a Directive with an Object as an Attribute Parameter

When I use $compile to create and bind a directive, how can I also add a variable as an attribute? The variable is an object.

var data = {
    name: 'Fred'
};

var dirCode = '<my-directive data-record="data"></my-directive>';

var el = $compile(dirCode)($scope);

$element.append(el);

And myDirective would be expecting:

...
scope: {
    record: '='
},
...

I have tried doing

 `var dirCode = '<my-directive data-record="' + data + '"></my-directive>';` 

instead too.

Upvotes: 10

Views: 5328

Answers (1)

sielakos
sielakos

Reputation: 2404

It is quite easy, just create new scope and set data property on it.

angular.module('app', []);

angular
  .module('app')
  .directive('myDirective', function () {
    return {
      restrict: 'E',
      template: 'record = {{record}}',
      scope: {
        record: '='
      },
      link: function (scope) {
        console.log(scope.record);
      }
    };
  });

angular
  .module('app')
  .directive('example', function ($compile) {
    return {
      restrict: 'E',
      link: function (scope, element) {
        var data = {
          name: 'Fred'
        };
        
        var newScope = scope.$new(true);
        newScope.data = data;

        var dirCode = '<my-directive data-record="data"></my-directive>';

        var el = $compile(dirCode)(newScope);
    
        element.append(el);
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>

<div ng-app="app">
  <example></example>
</div>

Upvotes: 14

Related Questions