通过 angular 中的指令访问 watch 中的变量

Access a variable inside watch by a directive in angular

我是 angular 的新手,在使用手表时遇到了一些问题。我正在观察控制器内的一个变量。一旦变量的值发生变化,我想将这个改变的值发送到一个指令。

这里是手表功能:

$scope.$watch("comboDetail", function(newValue, oldValue) {
  $scope.overlayProductCard = $scope.comboDetail.collectionCd;
  console.log("$scope.overlayProductCardWithinWatch", $scope.overlayProductCard);
}

还有我的指令:(为了便于阅读而删减)

return {
scope: {
      productCard: '='
    },
    restrict: 'E',
    templateUrl: appVersionFactory.getViewBaseUrl() + '/assets/partials/tv/tv-overlay-link.html',
    replace: true,
    link: function($scope, iElm, iAttrs, controller) {
      console.log("$scope.productCard", $scope.productCard);

  };

但是,$scope.productCard returns 对我来说是未定义的,而 $scope.overlayProductCardWithinWatch returns 我是正确的数据。

如何在指令中接收此数据?

试试这个:

link: function($scope, iElm, iAttrs, controller) {
  scope.$watch('productCard', function (newValue) {
    console.log("$scope.productCard", newValue);
  })
};

并在此之前通过 HTML 中的元素标记传递 productCard,例如:
data-product-card="overlayProductCard"

假设我有像 <test param="controllerParam"></test> 和模板 <div>{{param}}</div> 这样的指令。如果我在控制器中更改 controllerParam,我不需要 watch/something 否则 - 指令将获得新价值。如果每次更改时我都想在指令中记录新值 - 那么我需要在指令中观察。

Link 函数对每个元素执行一次,因此您只记录一次变量值。 (初一)