3

我正在尝试检测 AngularJS (1.7.2) 指令中双向绑定范围的更改。

// pagination.js (directive)
app.directive("pagination", ($rootScope) => {
  return {
    templateUrl: "/shared/filters/pagination/pagination.html",
    scope: {
      filter: "="
    },
    link: function($scope, element, attrs) {

      $scope.$watch("filter", value => {
        console.log(value); // first time works, later it's undefined
      });

    }
  }
});

// parent.html 
<pagination filter="filter"></pagination>

// parent.js 
$scope.filter = {
  status: "All"
};

$scope.filter 正在通过函数进行更改,该函数也位于 parent.js 文件中:

$scope.someFunction = () => {
  $scope.filter.status = "Pending";
  // this should fire the $scope.$watch event in the pagination.js (directive)
  // however this doesn't get applied
};

如何使范围被监听来自其他指令的更改?

4

1 回答 1

2

使用更深的观察深度:

  $scope.$watch("filter", value => {
      console.log(value); // first time works, later it's undefined
  ̶}̶)̶;̶̶
  }, true);

有关信息,请参阅AngularJS 开发人员指南 -$scope观察深度

于 2018-11-11T20:02:13.873 回答