【问题标题】:Angular directive 1 way binding is working but 2 way binding is notAngular 指令 1 方式绑定有效,但 2 方式绑定无效
【发布时间】:2017-04-12 17:47:21
【问题描述】:
  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 的对象/值绑定到指令!

指令:

 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 一起传递 // 打印出 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

发生了什么事?

【问题讨论】:

  • 所以它的行为就像是一个字符串绑定 (@)。好像有些东西没有得到正确的保存。尝试单向箭头 (
  • 不要在 Angular 表达式中使用 {{ }} 插值。它们在属性@ 绑定中存在问题。不要使用双向= 绑定。
  • 那么我做错了什么,不要做 {{}} 并且 = 不起作用
  • 双向= 绑定有效。人们每天都在使用它。
  • 哦,我需要使用 scope.code 代替 attrs.code 吗?

标签: angularjs angularjs-directive angularjs-scope angular-directive


【解决方案1】:

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

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

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

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

如果要获取属性的插值,即使不在隔离范围内,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);
  });
}

【讨论】:

    猜你喜欢
    • 2015-02-18
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2011-06-04
    • 2019-04-08
    • 1970-01-01
    • 2011-05-19
    • 2016-08-14
    相关资源
    最近更新 更多