Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to attributes in prototypically inherited scope

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.

like image 655
Yousef Avatar asked Nov 10 '22 06:11

Yousef


1 Answers

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;
     });
}
like image 178
pixelbits Avatar answered Nov 15 '22 10:11

pixelbits