Directular Corner Templates

I am trying to make a directive with different patterns based on the scope value.

This is what I have done so far and I don’t know why http://jsbin.com/mibeyotu/1/edit is not working

HTML element:

<data-type content-attr="test1"></data-type> 

Directive

 var app = angular.module('myApp', []); app.directive('dataType', function ($compile) { var testTemplate1 = '<h1>Test1</h1>'; var testTemplate2 = '<h1>Test2</h1>'; var testTemplate3 = '<h1>Test3</h1>'; var getTemplate = function(contentType){ var template = ''; switch(contentType){ case 'test1': template = testTemplate1; break; case 'test2': template = testTemplate2; break; case 'test3': template = testTemplate3; break; } return template; }; var linker = function(scope, element, attrs){ element.html(getTemplate(scope.content)).show(); $compile(element.contents())(scope); }; return { restrict: "E", replace: true, link: linker, scope: { content:'=' } }; }); 
+57
angularjs angularjs-scope angularjs-directive
Apr 14 '14 at 16:21
source share
4 answers

1) You pass the content as an attribute to your html. Try the following:

 element.html(getTemplate(attrs.content)).show(); 

instead:

 element.html(getTemplate(scope.content)).show(); 

2) part of the directive data is collected, so you should use something else. Instead of a data type, for example. Datan type.

Here's the link:

http://jsbin.com/mibeyotu/6/edit

+12
Apr 14 '14 at 16:34
source share

You can set the template property of a directive definition object for a function that will return your dynamic template:

 restrict: "E", replace: true, template: function(tElement, tAttrs) { return getTemplate(tAttrs.content); } 

Please note that at the moment you do not have access to the area, but you can access the attributes through tAttrs .

Now your template is determined before the compilation stage, and you do not need to manually compile it.

+104
Apr 14 '14 at 16:40
source share

You can also do this very simply:

 appDirectives.directive('contextualMenu', function($state) { return { restrict: 'E', replace: true, templateUrl: function(){ var tpl = $state.current.name; return '/app/templates/contextual-menu/'+tpl+'.html'; } }; }); 
+20
Nov 20 '14 at 21:27
source share

If you need to load a template based on $scope variables, you can do this with ng-include :

 .directive('profile', function() { return { template: '<ng-include src="getTemplateUrl()"/>', scope: { user: '=data' }, restrict: 'E', controller: function($scope) { //function used on the ng-include to resolve the template $scope.getTemplateUrl = function() { //basic handling if ($scope.user.type == 'twitter') { return 'twitter.tpl.html'; } if ($scope.user.type == 'facebook') { return 'facebook.tpl.html'; } } } }; }); 

Link: https://coderwall.com/p/onjxng/angular-directives-using-a-dynamic-template

+9
Jun 13 '16 at 5:31
source share



All Articles