0

I'm new to angular and can't figure out how to call a directive function from the template. I have some fuctionality that will be reused throught the app and figured I would just make a directive with all the functionlity needed, that can easily be shared accross different modules. While searching for answers I came across this post: how-to-call-a-method-defined-in-an-angularjs-directive which seems like a good solution. However, I can't seem to figure out why my directive method showPolicy() is not being called.

// controller:

(function(){
'use strict';

angular.module('releaseAppsModule')
.controller('releaseAppsController', releaseAppsController);

releaseAppsController.$inject = ['$rootScope', 
'storageFactory', 
'releaseAppsFactory',
'$modal',
'$translate',
'getIconFactory',
'$scope',
'$filter'];

function releaseAppsController($rootScope, storageFactory, releaseAppsFactory, $modal, $translate, getIconFactory, $scope, $filter) {

  var vm = this;
  vm.policyControl = {};
  ...

// controller template:

<tr ng-repeat="policyRelease in regionRelease.policyReleases | orderBy:vm.orderByField:vm.reverseSort" ng-if="policyRelease.status == 'NEW' || policyRelease.status == 'SCHEDULED'">
<td>
<policy control="vm.policyControl" release-item="policyRelease" class="release-apps-app-btn app-release-data"></policy>
</td>

// directive:

(function(){
'use strict';

angular.module('myApp')

.directive('policy', policy)

    function policy() {

        var directive = {
            restrict: 'E',
            link: link,
            replace: true,
            scope: {
                releaseItem: '=',
                control: '='
            },
            template: '<a ng-click="vm.policyControl.showPolicy({releaseItem: releaseItem});">{{ releaseItem.policy.name }}</a>'
        };

        return directive;

        function link(scope, el, attr) {
            scope.internalControl = scope.control || {};
            scope.internalControl.showPolicy = function (releaseData) {
                ...
            } // showPolicy

            scope.internalControl.showPolicyModal = function(response, releaseData) {
                ...
            } // showPolicyModal

        } // link

    } // policy

})();
Community
  • 1
  • 1
neridaj
  • 2,143
  • 9
  • 31
  • 62

1 Answers1

1

In your template, you're trying to call vm.policyControl.showPolicy() which is undefined on your current directive scope, as Angular is attempting to find

[directiveScope].vm.policyControl.showPolicy()

You'll need to change the ng-click function to internalControl.showPolicy(), as that is referencing the actual object that the directive's scope has available.

Joe Pontani
  • 451
  • 4
  • 13