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

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

问题描述

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

HTML页面工作

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

以上以一种方式将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('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

这就是问题所在,当我切换到我急需的双向数据绑定时

接下来是问题:

从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,在使用隔离范围和双向出价'='运算符时,请将该值插入到父范围内,以获取可以通过链接函数上的scope参数访问的实际值.

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 {{ }}

如果要获取属性的插值,即使不在隔离范围内,请

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天全站免登陆