Angular 指令 1 路绑定有效,但 2 路绑定无效 [英] Angular directive 1 way binding is working but 2 way binding is not

查看:26
本文介绍了Angular 指令 1 路绑定有效,但 2 路绑定无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

HTML 页面正在运行

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

以上通过 1 种方式将 PNLC 的对象/值绑定到指令!

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

指令:

 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 of console.log('ldcCode', attrs.code); //打印出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

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

接下来是问题:

从 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

ldcCode detail.program.ldcCode

这是怎么回事?

推荐答案

attr 链接函数参数似乎显示了赋予属性的原始值.

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

Angular,在使用隔离作用域和双向 '=' 运算符时,取该值并将其插入到父作用域上,以获得您可以通过链接函数上的作用域参数访问的实际值.

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.

参考 $compile.directive.Attributes 在 Angular 文档中:

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

指令编译/链接函数之间的共享对象包含规范化的 DOM 元素属性.这些值反映了当前绑定状态{{}}

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

如果你想获取属性的插值值,即使不在隔离范围内,您可以在其上使用 $observe 方法 :

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

这篇关于Angular 指令 1 路绑定有效,但 2 路绑定无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆