Adding custom directives
by scyrizales
HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.js"></script>
<div ng-app="test" ng-controller="Controller1">
<div ng-repeat="l in myList">
{{ l.title }}
<div compile="l.content"></div>
</div>
</div>
JavaScript
angular.module("test", ["ngSanitize"])
.controller("Controller1", ['$scope', function($scope) {
$scope.myList = [{
title: 'Angular1',
content: '<angular-one></angular-one>'
}, {
title: 'Angular2',
content: '<div angular-two=""></div>'
}];
}])
.directive('compile', ['$compile', function($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
}])
.directive("angularOne", function() {
return {
restrict: "EA",
link: function($scope) {
$scope.value = "angular-one-directive";
},
template: "<div>{{ value }}</div>"
}
})
.directive("angularTwo", function() {
return {
restrict: "EA",
link: function($scope) {
$scope.value = "angular-two-directive";
},
template: "<div>{{ value }}</div>"
}
});