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:
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?
The directive scope uses prefixes to achieve that. Using prefixes helps establish a two-way or one-way binding between parent and directive scopes, and also make calls to parent scope methods. To access any data in the parent scope requires passing the data at two places – the directive scope and the directive tag.
Pre-linking function Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. Post-linking function Executed after the child elements are linked.
The $compile service is the service to use for compilation. Invoking $compile against markup will produce a function you can use to bind the markup against a particular scope (what Angular calls a linking function). After linking, you'll have DOM elements you can place into the browser.
The ng-transclude directive facilitates AngularJS to capture everything that is put inside the directive in the markup and use it somewhere in the directive's template. Syntax: <ng-transclude.
Angular 1.1.4 released in last few weeks added 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 directive docs for version 1.1.4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With