AngularJS - $ compiles a directive with an object as an attribute parameter

When I use $compile to create and bind directives, how can I add a variable as an attribute? A 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 will wait:

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

I tried to do

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

also.

+5
source share
1 answer

It's quite simple, just create a new area and set the 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> 
+8
source

All Articles