user6321478
user6321478

Reputation:

Angular directive 1 way binding is working but 2 way binding is not

  1. I am not using scope in my controller as i use controller as etc..
  2. I have proof of concept that plunker without scope is working
  3. 1 way binding is working
  4. 2 way binding is NOT working - shows literal value

HTML page WORKING

 Here: {{detail.program.ldcCode}}  SHOWS   "Here: PNLC"
 <lcd-code code="{{detail.program.ldcCode}}"></lcd-code>

Above passes in 1 way binding of that object/value of PNLC to Directive !

Directive :

 return {
        replace: true,
        restrict: "EA",
        scope: {
            code: "@"
        },
         link: function (scope, element, attrs) {
            console.log('ldcCode', attrs.code);  // PRINTS out PNLC

Thus the above 1 way binding works with passing in {{detail.program.ldcCode}} as an expression , and then in directive the code: "@" along with console.log of console.log('ldcCode', attrs.code); // PRINTS out PNLC

So HERE IS THE PROBLEM, when i switch to my much needed two way data binding

Next is the issue:

Pass from HTML to directive WITHOUT Expression

<lcd-code code="detail.program.ldcCode"></lcd-code>

Directive

scope: {
      code : "="
},
link: function (scope, element, attrs) {

            console.log('ldcCode', attrs.code);
           LITERALLY this prints to chrome dev console as below in bold

ldcCode detail.program.ldcCode

What is going on?

Upvotes: 1

Views: 456

Answers (1)

elpddev
elpddev

Reputation: 4494

It seems that the attr link function parameter is showing the raw value given to the attribute.

Angular, when using the isolated scope and the two way biding '=' operator, take that value and interpolate it on the parent scope to get the actual value that you can access via the scope parameter on the link function.

Reference to the $compile.directive.Attributes in Angular docs:

A shared object between directive compile / linking functions which contains normalized DOM element attributes. The values reflect current binding state {{ }}

If you want to get the interpolate value of the attribute, even not on the isolated scope, you can use the $observe method on it:

function linkingFn(scope, elm, attrs, ctrl) {
  // get the attribute value
  console.log(attrs.ngModel);

  // change the attribute
  attrs.$set('ngModel', 'new value');

  // observe changes to interpolated attribute
  attrs.$observe('ngModel', function(value) {
    console.log('ngModel has changed value to ' + value);
  });
}

Upvotes: 0

Related Questions