good widget template
by merganser
HTML
<div ng-controller="MyCtrl">
<div dynamic="{{directives}}" ng-model="text"></div>
<button ng-click="add('<one/>')">Add One</button>
<button ng-click="add('<two/>')">Add One</button>
<button ng-click="modifyText()">change</button>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.directive('one', function () {
return {
scope: {
},
restrict: 'AE',
replace: true,
template: '<div><p>{{text}}</p><button ng-click="changeText()">test</button></div>',
link: function (scope, elem, attrs) {
scope.changeText = function (txt) {
scope.index += 1;
scope.text = scope.index;
};
scope.restore = function () {
scope.text = "test",
scope.id = 1,
scope.index = 1
};
scope.restore();
}
}
});
myApp.directive('two', function () {
return {
restrict: 'E',
replace: true,
template: '<div>Directive two</div>'
}
});
myApp.directive('dynamic', function ($compile, $parse) {
return {
restrict: 'A',
replace: true,
link: function (scope, element, attr) {
attr.$observe('dynamic', function (val) {
element.html('');
var directives = $parse(val)(scope);
angular.forEach(directives, function (directive) {
element.append($compile(directive)(scope));
});
});
}
};
});
myApp.controller('MyCtrl', function ($scope) {
$scope.directives = ['<one/>', '<two/>'];
$scope.add = function (directive) {
$scope.directives.push(directive);
}
$scope.modifyText = function () {
var last = $scope.directives[$scope.directives.length - 1];
console.log(last);
last.changeText("tt");
}
});