Chris
Chris

Reputation: 155

Angular call controller function from nested custom directive

I could use some help. I have a controller containing a function called "loadInformation()". Inside this controller I use a service which is doing some DOM-Manipulation using custom directives. These are the directives:

First custom Directive:

angular.module('...').directive('ngInputString', function () {
return {
restrict: 'AE',
replace: 'true',
scope: {
  savedInformation: '=',
  type: '@',
  values: '='
},
templateUrl: 'directives/templates/inputString.html',
link: function (scope, element, attrs) {
  scope.filterOb = {ttype: scope.type};
}
}
});

HTML file:

<div>
<input ttype="{{type}}" type="text" placeholder="{{param.name}}"         value='{{param.value}}'
     class='clean-input form-control'/>
 <ng-saved-information type="STRING" saved-information="savedInformation"></ng-saved-information>
 </div>

Nested custom directive:

angular.module('semtrosApp').directive('ngSavedInformation', function    () {
return {
restrict: 'AE',
replace: 'true',
scope: {
  savedInformation: '=',
  type: '@'
},
template: '<ul><li ng-repeat="information in savedInformation |    filter:filterOb">{{information.value}}<button type="button" ng-click="..?..">Use Information</button></li></ul>',
link: function (scope, elem, attrs) {
  scope.filterOb = {ttype: scope.type};
}
}
});

When I dont use nested directives, it works just fine with that piece of code:

elem.bind('click', function() {
    scope.$apply(function() {
      scope.loadInformation();
    });
  });

But when they are nested, the second custom diretive is just looking inside the scope of the parent directive. Any idea how to pass through the function call?

Upvotes: 0

Views: 180

Answers (1)

Frank Modica
Frank Modica

Reputation: 10516

It looks like the ngInputString directive already takes in some data and passes it down to ngSavedInformation. Why not have it take in a loadInformation callback as well and pass it down?

angular.module('...').directive('ngInputString', function () {
  return {
    scope: {
      savedInformation: '=',
      type: '@',
      values: '=',
      loadInformation: '&'
    },
    // etc
  }
});

 <ng-saved-information type="STRING" saved-information="savedInformation" load-information="loadInformation()"></ng-saved-information>

 angular.module('semtrosApp').directive('ngSavedInformation', function () {
   return {
     scope: {
       savedInformation: '=',
       type: '@',
       loadInformation: '&'
     },
     // etc
   }
 });

Also, instead of manually creating a click handler, you could do the following in the template:

ng-click="loadInformation()"

Upvotes: 1

Related Questions