Sandeep
Sandeep

Reputation: 605

AngularJs custom directive used twice in one controller with $watch

Hi I have a controller which has a param called refresh and a $watch

app.controller (..., []) {
  $scope.refresh = false;

  $scope.$watch('refresh', function() {
            if(!$scope.refresh) return;
             $scope.apiCall(true);
            
   }, true);
}

I have a directive where refresh is used.

app.directive('dirA', () => {
  return {
    restricts: E,
    scope: {
      refresh: '=',
      .....
    },
    templateUrl: 'location of template',
    controller: [..., {
        function test() {
          $scope.refresh = false;
          // API call here
          fetch('/test', () => {
            this.refresh = true;
          )}
        }
    }]
  }
})

In my Controller's template I am using this directive twice like

<dirA refresh="refresh"/>
<dirA refresh="refresh"/>

Issue that I am facing is when refresh changes from first instance of directive, $watch is called but same is not happening from second instance.

I am pretty new to angularjs, Please help if possible

Upvotes: 0

Views: 37

Answers (1)

Mark Clark
Mark Clark

Reputation: 535

When you declare a controller in a directive, you also need to bind the isolate scope of your directive using bindToController.

Here is an article that explains bindToController

I also took the time to write a plunkr that demonstrates with the code you provided how this should probably look.

Upvotes: 1

Related Questions