Load Teemplate Dynamically in AngularJs
This snippet shows, how we can load external template or page in angularJs. Follow attuts for more tutorial on Angularjs
by abdul quadir
HTML
<h1><a href="http://attuts.com">Full tutorial - How to load template dynamically in AngularJs</a></h1>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
<script>
angular.module('mainapp', []);
angular.module('mainapp').controller('appcontroller', function($scope) {
$scope.content = {
type: 'text',
data: {
content: 'Hello World'
}
};
});
angular.module('mainapp').directive('customElement', function($http, $compile) {
var render = function($elem, $scope, data) {
var elementScope = $scope.$new(true);
angular.forEach(data.data, function(value, key) {
elementScope[key] = value;
});
// for this example, using attuts home page else script would be like
//$http.get('template-'+data.type+'.html')
$http.get('http://attuts.com').then(function(response) {
$elem.html(response.data);
$compile($elem.contents())(elementScope);
}, function() {
console.error('template', data.type, 'not found.');
});
};
return {
restrict: 'E',
scope: true,
link: function($scope, elem, attrs) {
var $elem = $(elem);
$scope.$watch(attrs.element, function(now) {
if(now) {
render($elem, $scope, now);
}
});
}
}
});
</script>
<div ng-app="mainapp" ng-controller="appcontroller">
<custom-element element="content"></custom-element>
</div>