更新范围时不调用 Angular 指令

Angular directive not getting called when scope is updated

本文关键字:Angular 指令 调用 范围 更新      更新时间:2023-09-26

我有一个正在修改变量的作用域:

$scope.showContext = function(context) {
        $scope.currentContext = context;
....
}

我在页面上有一个指令:

<div org-chart workflow="currentContext" />

我有一个指令:

var OrgChartDirective = function($timeout) {
    return {
        restrict : 'AE',
        scope : {
            workflow : '=',
        },
        link : function(scope, element, attrs) {

            if (scope.workflow != null) {
                console.log("**________________________________**");
                console.log(scope);
            } else {
                alert("Workflow is null");
            }
      ....

加载页面时,收到工作流为空的警报。

当我运行更新 $scope.currentContext 的范围函数时,没有其他反应。 应该再叫一次吧?

编辑说:我在页面上有这个,它确实表明在我调用 scope 方法后正在设置变量:

Workflow----> {{currentContext.workflow}}

您必须观察/观察链接函数中的属性更改,如下所示:

attrs.$watch('workflow', function() {
    //do whatever logic you want
});

在此处阅读有关观察者和观察者以及如何使用它们的更多信息:关于观察者和观察者的本纳达尔教程

试试这个要点:观察者和观察者的要点

听从 charlietfi,尝试使用观察者

link : function(scope, element, attrs) {
  scope.$watch('workflow', function(val) {
  ...
  });