简体   繁体   中英

Angular directive not getting called when scope is updated

I have a scope that is modifying a variable:

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

I have a directive on the page:

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

I have a directive:

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");
            }
      ....

When I load the page, I get the alert that the workflow is null.

When I run the scope function that updates $scope.currentContext , nothing else happens. It should be called again, right?

Edited to say: I have this on the page and it does show that the variable is getting set after I call the scope method:

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

Defering to charlietfi, try with a watcher

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

You will have to watch/observe for the property change in the link function like this:

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

Read more about observers and watchers and how you can use them here: Ben naddal tutorial on observers and watchers

Try this gist: Gist for observers and watchers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM