Angular 指令 1 种方式绑定有效,但 2 种方式绑定无效

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

  1. 我没有在我的控制器中使用范围,因为我使用控制器等。
  2. 我有概念证明没有范围的 plunker 正在工作
  3. 1 种绑定方式有效
  4. 2 种绑定方式无效 - 显示文字值

HTML 页工作中

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

以上以一种方式将 PNLC 的 object/value 绑定到指令!

指令:

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

因此,上述 1 种绑定方式将 {{detail.program.ldcCode}} 作为表达式传入,然后在指令中将 code: "@"console.log('ldcCode', attrs.code); console.log [=38] =]// 打印出 PNLC

问题来了,当我切换到我急需的双向数据绑定时

接下来是问题:

从 HTML 传递到不带表达式的指令

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

指令

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

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

ldc代码detail.program.ldcCode

这是怎么回事?

attr link 函数参数似乎显示了赋予属性的原始值。

Angular,当使用独立作用域和双向竞价“=”运算符时,获取该值并将其插值到父作用域以获得您可以通过作用域参数访问的实际值link 函数。

参考 Angular 文档中的 $compile.directive.Attributes

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

如果你想获取属性的插值,即使不在隔离范围内,you can use the $observe method就可以了:

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);
  });
}