AngularJS directive : compile template and watch scope
angularjs, angularjs-directive, javascript
Solution
I think change your directive by :
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);
}
})
Problem
I writing a pretty complex application on Angularjs. This is already big enough to confuse me. I research Angular deeper and I see 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 several problems: - My template is complicated, I have part of template which going in the link function dynamically - I need to append compiled template to the element, not to replace. - With concept above my template are appended without any interpolation... So my code is looking like that in simplified view: ``` 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 is: How to compile my template with scope variables? How to watch scope variables? Should I split my directive for two? If I should, how to do it in right way?