Attribute binding in a prototypically inherited area

I would like to create a directive with a prototypically inherited scope (i.e. scope = true), but also set an attribute binding similar to the following when setting up an isolated scope:

scope = {
'varname':'=attrname'
}

My current solution is to set scope = true and configure attribute binding in the following lines in the link function:

scope. $ watch (element.attr ('attrname'), function (val) {scope.varname = shaft;}); // watch changes scope.varname = Volume $ Eval (element.attr ('attrname')). // initialize

Although this does the trick, it does not seem very elegant. What approach do you suggest?

I find that amazing angularjs seems to expect that in the directive you won't need attribute binding when setting up a new legacy scope.

+4
source share
3 answers

I know what you mean, and I agree with you. It would be nice if Angular provided a convenient structure for a directive to configure two-way model binding between the parent sphere variable and the child variable and still support prototype region inheritance.

To achieve the same effect as in the selected area:

 scope = {'varname':'=attrname'} 

you can configure the binding of a two-way model in your directory link:

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;
     });
}
+1
source

I think you are looking for this code in a link function:

 var yourVar = $parse(attrs.attrName)(scope);  // Parse the attribute with a specific scope context

You will then pass the attributes, as you did, using a separate scope directive, but you can still use the prototype inherited scope.

, , , . , , , . ( , , , , )

, $parse, : https://docs.angularjs.org/api/ng/service/ $parse

, , , .

0

, , . , $scope.$observe() $scope.$watch():

scope.$observe('attrname', function(val) {
    scope.varname = $parse(val)(scope);
});
0

Source: https://habr.com/ru/post/1545203/


All Articles