Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 525
kenshin9 Avatar asked May 24 '16 17:05

kenshin9


People also ask

What does $compile do in AngularJS?

Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.

Which directive initializes an AngularJS application?

The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

Which directive is used to assign values to the variables in AngularJS?

ng-init directive It is used to declare and assign values to the variables for an AngularJS application.

Which directive initializes an AngularJS application Mcq?

The ng-app directive is used to initialize the AngularJS application.


1 Answers

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>
like image 59
sielakos Avatar answered Sep 27 '22 22:09

sielakos