Angular directive does not update as scope updates

风格不统一 提交于 2020-01-25 04:22:45

问题


I'm puzzled by the apparent failure of my directive to update whenever its scope updates.

I want to add up the characters in 3 different form fields, subtract that length from 29 (cause of reasons...), and output that total as a string in a piece of DOM contained in the directive template.

Directive:

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

Reference to directive in index.html:

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

This works sort-of: I can step through the directive when the page loads and watch scope.remainingChars get set to the right number when the directive loads the first time. However, if I change the transaction object, the number never updates.

I can get the behavior I want if I set up a $watchCollection on the transaction object, but I should be able to just pass that object into the isolate scope using the '=' two-way-binding mechanism. Yet the directive runs 1 time, calculates correctly, and never changes it's value again even when I update the form fields it's model is bound to.

Everything is happening on scope, so I don't believe I need to run $apply(), and I need this to be done in a directive because I need to apply styling to the DOM based on the number (positive / negative). Otherwise I would just have something like <span>{{29 - transaction.checkType.length - transaction.checkNumber.length - transaction.depositnote.length}} remaining</span> in index.html.

What am I missing here? Thanks!


回答1:


link is only run once, during the initial directive link phase.

There's several ways to do this though: Have a function on the scope called remainingChars(), and return the correct amount there. Then in your template have {{remainingChars()}}

Second, you could have a watch expression:

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

Or third, have some kind of ng-change event handler which updates the remainingchars variable.

ng-change="calcRemanining()"


来源:https://stackoverflow.com/questions/27393759/angular-directive-does-not-update-as-scope-updates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!