var app = angular.module('plunker', []);
app.controller('MainCtrl', function() {
var vm = this;
vm.message = 'Hi there';
});
app.directive('myDirective', function() {
return {
restrict: 'E',
template: '<pre>{{ property | json }}</pre>',
require: '^form',
scope: {
property: '='
},
// @ngInject
link: function($scope, iElement, attributes, FormCtrl) {
// make the form available in the template
$scope.form = FormCtrl;
},
// @ngInject
controller: function($scope) {
var vm = this;
// resolve the property name
vm.resolvedProperty = $scope.property.$name;
},
controllerAs: 'valMsgCtrl'
};
});
app.directive('dynamicAddDirective', function($compile) {
return {
restrict: 'A',
scope: true,
require: 'ngModel',
compile: function(tElement, attributes) {
return function($scope, iElement, attributes, ngModel) {
$scope.value = attributes.ngModel;
var template = '<my-directive property="' + $scope.value + '"></my-directive>';
var el = angular.element($compile(template)($scope));
el.insertAfter(iElement);
}
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery@*" data-semver="2.1.3" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script data-require="angular.js@1.3.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js" data-semver="1.3.7"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as vm">
<form>
<strong>Result:</strong>
<input type="text" ng-model="vm.message" dynamic-add-directive>
<hr/>
<my-directive property="vm.message"></my-directive>
</form>
</body>
</html>
/* Put your css in here */