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

1

10

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.

Moonseed answered 24/5, 2016 at 17:40 Comment(1)
var data = {} needs to be attached to your controller scope to get two way binding. If you dont care about two way binding a hackier way is to do <directive data-record=`${JSON.stringify(data)}`></directive>Liebermann
C
14

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>
Chemush answered 24/5, 2016 at 19:27 Comment(1)
Thank you, that finally made the penny drop. The scope parameter is the parent scope, not the scope that is injected into the directive.Stammel

© 2022 - 2024 — McMap. All rights reserved.