I'm trying to create a directive to load a custom template, but if the custom doesn't exists, load the default template.
Here is my code:
HTML:
<my-include src="path/to/template.html"></my-include>
Directive:
angular.module('app')
.directive("myInclude", function ($compile) {
return {
restrict: 'CAE',
replace: true,
scope: {
src: '@',
},
link: function (scope, iElement, iAttrs, controller) {
scope.$on("$includeContentError", function (event, args) {
scope.src = args.replace('/custom', '').replace("'", '');
});
scope.$on("$includeContentLoaded", function (event, args) {
scope.src = args.replace("'", '');
});
},
template: '<div class="include-container" ng-include="src"></div>'
};
})
;
The problem I have is that... my template is not showing... When I debug it, it goes to the directive and replace the src. But the html I get is the following :
<div class="include-container ng-scope" ng-include="src" src="path/to/template.html"><div class="main-information-content ng-scope">
</div>
Any idea how I could solve this issue ? I'm guessing it's because of the "ng-include='src'", where "src" is not replaced by the path... How to fix it ?
EDIT:
I tried to put this template :
template: '<div class="include-container" ng-include="{{ src }}"></div>'
but I get this error:
Error: [$parse:syntax] http://errors.angularjs.org/1.5.0/$parse/syntax?p0=%7B&p1=invalid%20key&p2=2&p3=%7B%7Brc%20%7D%7D&p4=%7B%src%20%7D%7D
EDIT 2: When I put this as a template :
template: '<div class="include-container" ng-include="tmpSrc"></div>'
and replace scope.src
by scope.tmpSrc
, the ng-include value is good now, BUT the replaced template in my html view is commented out... Why ?
EDIT 3:
Using your snippet, here is an idea of what I need to do:
angular
.module('app', [])
.directive("myInclude", function($compile) {
return {
restrict: 'CAE',
replace: true,
scope: {
src: '@',
},
link: function(scope, iElement, iAttrs, controller) {
scope.$on("$includeContentError", function() {
scope.src = 'error-template.html';
});
scope.$on("$includeContentLoaded", function(event, args) {
// No need to do anything - the content has loaded.
});
},
template: '<div class="include-container" ng-include="src"></div>'
};
})
.controller('mainController', ['$scope', '$http',
function($scope, $http) {
// Is the content loaded ?
$scope.state = 'loading';
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="app">
<div>
This will show the correct template:
<my-include src="path/to/template.html"></my-include>
</div>
<div>
This will show an error template:
<div ng-controller="mainController as main">
<my-include src="something/that/does/not/exist.html"></my-include>
</div>
</div>
<script type="text/ng-template" id="path/to/template.html">
<h1>I want to display state : {{ state }}</h1>
</script>
<script type="text/ng-template" id="error-template.html">
<h1>Hello from "error-template.html"</h1>
</script>
</div>