AngularJS Directive: compile template and viewport

I am writing a rather complicated application in Angularjs. This is big enough to embarrass me. I am exploring Angular deeper and I can see that my code is bad. I understand this concept:

module.directive('createControl', function($compile, $timeout){ scope: { // scope bindings with '=' & '@' }, template: '<div>Template string with binded {{ variables }}</div>', link: function(scope, element, attrs){ // Function with logic. Should watch scope. } 

I have a few problems:

  • My template is complex, I have part of a template that works dynamically in the link function
  • I need to add a compiled template to the element, not replace it.
  • With the concept above, my template is added without any interpolation ...

So, my code looks in a simplified form:

 module.directive('createControl', function($compile, $timeout){ scope: { var1: '@var1', var2: '@var2', var3: '@var3' }, template: '<div>{{ var1 }} {{ var3 }}</div>', link: function(scope, element, attrs){ $('.someelement').on('event', function(){ var2 = 'SNIPPET'; // Need to watch it }); var3 = '<span>{{ var2 }}</span>'; } }) 

My questions:

How to compile my template with scope variables?

How to view scope variables?

Should I split my directive in two? If I have to, how to do it right?

+7
source share
2 answers

I think we will change your directive:

  module.directive('createControl', function($compile, $timeout){ scope: { var1: '=var1', var2: '=var2', var3: '=var3' }, template: '<div>{{var1}} {{var3}}</div>', link: function(scope, element, attrs){ $('.someelement').on('event', function(){ scope.var2 = 'SNIPPET'; // Need to watch it }); /*I do not see what you want to do*/ scope.var3 = $compile('<span>{{var2}}</span>')(scope); } }) 
+3
source

Angular 1.1.4, released over the past few weeks, has added the ability for template to access attributes in directives:

Example:

 app.directive('mytest',function(){ return { restrict:'E', template:function( elem,attrs ){ return '<div>'+attrs.a+' '+attrs.b+'</div>'; } } }); 
 <mytest a="Hello" b="World"></mytest> 

Demo

See directory documents for version 1.1.4

+10
source

All Articles