【问题标题】:Angular directive does not update as scope updatesAngular 指令不会随着范围更新而更新
【发布时间】:2014-12-10 05:14:44
【问题描述】:

我对我的指令在其范围更新时明显未能更新感到困惑。

我想将 3 个不同表单字段中的字符相加,从 29 中减去该长度(原因...),并将该总和输出为指令模板中包含的一段 DOM 中的字符串。

指令:

    return {
      restrict: 'AE',
      replace: true,
      templateUrl: '<span>{{remainingChars}} remaining</span>',
      scope: {
        checktype: '=',
        checknumber: '=',
        depositnote: '='
      },
      link: function (scope, elem) {
        scope.remainingChars = 29 - scope.checktype.length - scope.checknumber.length -             scope.depositnote.length;
      }
    }

对 index.html 中指令的引用:

      <deposit-note
          checknumber="transaction.checkNumber"
          checktype="transaction.checkType"
          depositnote="transaction.depositNote" />

这有点工作:我可以在页面加载时单步执行指令,并在第一次加载指令时观察scope.remainingChars 设置为正确的数字。但是,如果我更改事务对象,则数字永远不会更新。

如果我在 transaction 对象上设置 $watchCollection,我可以获得我想要的行为,但我应该能够使用“=”双向绑定机制将该对象传递到隔离范围。然而,该指令运行了 1 次,计算正确,并且即使我更新了它的模型绑定到的表单字段,也永远不会再次更改它的值。

一切都在范围内发生,所以我认为我不需要运行 $apply(),我需要在指令中完成此操作,因为我需要根据数字(正 /消极的)。否则我只会在 index.html 中有类似 &lt;span&gt;{{29 - transaction.checkType.length - transaction.checkNumber.length - transaction.depositnote.length}} remaining&lt;/span&gt; 的内容。

我在这里缺少什么?谢谢!

【问题讨论】:

标签: javascript angularjs angularjs-directive


【解决方案1】:

链接仅在初始指令链接阶段运行一次。

不过,有几种方法可以做到这一点: 在作用域上有一个名为 remainingChars() 的函数,并在那里返回正确的数量。然后在你的模板中有{{remainingChars()}}

其次,你可以有一个监视表达式:

$scope.$watch(function() {
  // watch expression, fires the second function on change
  return transaction.checkNumber.length - transaction.depositnote.length}, function() {
  //update the remainingchars value here in the second function
})

或者第三个,有一些更新剩余字符变量的 ng-change 事件处理程序。

ng-change="calcRemanining()"

【讨论】:

  • 我知道链接函数只运行一次,但我希望它设置为 scope.checkType 等的引用会随着 $scope.transaction.checkType 的更新而自动持续和更新。我在那里离谱吗?即使我不使用隔离范围,我也会得到同样的意外行为。
  • 是的,这是不正确的。你只会用它来设置初始值
  • 谢谢 GBa... 我没有意识到我的 2-way binding 概念离我有多远。欣赏答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多