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.

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> Commented May 24, 2016 at 18:01

1 Answer 1

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>

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

1 Comment

Thank you, that finally made the penny drop. The scope parameter is the parent scope, not the scope that is injected into the directive.

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.