我是角色的新手,无法弄清楚如何从模板中调用指令函数。我有一些功能可以在应用程序中重复使用,并认为我只需要制作一个具有所需功能的指令,可以很容易地在不同的模块中共享。在搜索答案时,我发现了这篇文章:how-to-call-a-method-defined-in-an-angularjs-directive 这似乎是一个很好的解决方案。但是,我似乎无法弄清楚为什么我的指令方法showPolicy()没有被调用。
// 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>
//指令:
(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
})();
答案 0 :(得分:1)
在你的模板中,你试图调用当前指令范围未定义的vm.policyControl.showPolicy()
,因为Angular正在尝试查找
[directiveScope].vm.policyControl.showPolicy()
您需要将ng-click
函数更改为internalControl.showPolicy()
,因为它引用了指令范围可用的实际对象。