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.
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.
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.
ng-init directive It is used to declare and assign values to the variables for an AngularJS application.
The ng-app directive is used to initialize the AngularJS application.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With