I'd like to create a directive, with a prototypically inherited scope (i.e. scope=true), but also set up scope binding to attributes, similar to following when setting up an isolated scope:
scope = {
'varname':'=attrname'
}
My current solution is to set scope=true and set up the binding to the attributes along the following lines in the link function:
scope.$watch(element.attr('attrname'), function(val) { scope.varname = val; }); // watch changes scope.varname = scope.$eval(element.attr('attrname')); // initialize
Although it does the trick it doesn't seem to be very elegant. What approach do you suggest?
I find it surprising angularjs seems to expect that in a directive you wouldn't need attribute binding when setting up a new inherited scope.
I know what you mean and I agree with you. It would be nice if Angular provided a convenient framework for a directive to set-up two-way model binding between a parent scope variable and a child scope variable and still support prototypical scope inheritance.
To achieve the same effect as the following with isolated scope:
scope = {'varname':'=attrname'}
you can set up the two-way model binding within your directive's link function:
scope: true,
link: function(scope, element, attr) {
// when attrname changes in parent scope, update varname in current scope
scope.$parent.$watch(attr.attrname, function(newVal) {
scope.varname = newVal;
});
// when varname changes in current scope, update attrname in parent scope
scope.$watch('varname', function(newVal) {
scope.$parent[attr.attrname] = newVal;
});
}
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