异步上未更新指令作用域

Directive scope not updated on async

本文关键字:指令 作用域 更新 异步      更新时间:2023-09-26

这在这里似乎是一个相当常见的问题,但我似乎无法理解Angular中使用自定义指令的数据绑定。我使用的是1.4.8,这是我的代码:

<p data-ng-show="!main.resolved">Loading...</p>
<my-directive data-ng-hide="!main.resolved"
              data-file-reads="main.reads"></my-directive>

main.reads的值通过我的MainCtrl:上的$http检索

angular.module('myApp')
  .controller('MainCtrl', ['$http', '$scope', function($http, $scope) {
    this.resolved = false;
    this.currentTab = 0;
    $http.get('/my/api/call').then(res => {
      this.reads = res.data.file_reads;
      this.writes = res.data.file_writes;
      this.resolved = true;
    });
    $scope.$watch('main.reads', new => console.log(new)); // triggered twice
  }]);

现在,我的指令的代码只是在侦听fileReads属性的更改:

angular.module('myApp')
  .directive('myDirective', function () {
    return {
      restrict: 'E',
      scope: {
        fileReads: '='
      },
      template: '<div></div>',
      bindToController: true,
      controllerAs: 'ctrl',
      controller: ['$scope', 'files', function($scope, files) {
        const controller = this;
        $scope.$watch('fileReads', function(newVal) {
          console.log(newVal); // only triggered once
        });
      }]
    };
  });

我只得到一个值为undefinedconsole.log。当$http承诺解析并且fileReads的值在MainCtrl上更新时,我在指令控制器上没有得到更新。

现在,我已经多次遇到这种问题,怀疑这在某种程度上与$scope.$apply$digest周期有关,但我没有从外部来源或任何东西更新我的范围。

有什么提示吗?

我还没有找到更多关于具体原因的信息(我一定会在编辑这篇文章时编辑它),但现在用函数调用包装我的手表表达式做到了(我也用$watchCollection替换了我的$watch,但这只是次要的):

$scope.$watchCollection(() => this.fileReads, newVal => console.log(newVal));