是Angular的新手,我在我的应用程序中实现了一个指令。该指令有两个控件,它们调用两个不同的控制器方法(带参数)。我如何调用这些函数,因为我已经理解指令充当插件(或类似的)。参数设置也不起作用。这是我的代码
myDirective.directive('entityActions', function () {
return {
scope: {
entity: '=entityActions'
},
restrict: 'EA',
template: [
'<td>{{entity.EntityType}}</td>',
'<td>{{entity.Description}}</td>',
"<td class=''>",
"<a onclick='editentity(entity.EntityType)' class='btn btn-info btn-xs margin-right4px'>",
"<span class='glyphicon glyphicon-pencil'></span>",
"</a>",
"<a onclick='deleteEntity(entity.EntityType)' class='btn btn-danger btn-xs'>",
"<span class='glyphicon glyphicon-remove'></span>",
"</a>",
"</td>"
].join('')
}
});
任何人都可以帮助我
谢谢&amp;问候 Arjun Menon
答案 0 :(得分:1)
在Angular中,通信b / w指令和控制器必须通过服务/工厂完成。
所以让我们为以下内容创建一个服务:
.service('EntityService', function() {
this.editentity = function(type) {}; // define function here instead of controller
this.deleteEntity = function(type) {}; // define function here instead of controller
});
在现有控制器定义中注入此服务:
.controller('MyCtrl', ['$scope', 'EntityService', function($scope, EntityService) {
$scope.editentity = EntityService.editentity;
$scope.deletEentity = EntityService.deleteEntity;
}]);
最后,改变你的指令:
myDirective.directive('entityActions', function () {
return {
scope: {
entity: '=entityActions'
},
restrict: 'EA',
controller: function($scope, EntityService) {
$scope.deleteEntity = function(type) {
EntityService.deleteEntity(type);
};
$scope.editentity = function(type) {
EntityService.editentity(type);
}
},
template: [
'<td>{{entity.EntityType}}</td>',
'<td>{{entity.Description}}</td>',
"<td class=''>",
"<a ng-click='editentity(entity.EntityType)' class='btn btn-info btn-xs margin-right4px'>",
"<span class='glyphicon glyphicon-pencil'></span>",
"</a>",
"<a ng-click='deleteEntity(entity.EntityType)' class='btn btn-danger btn-xs'>",
"<span class='glyphicon glyphicon-remove'></span>",
"</a>",
"</td>"
].join('')
}
注意:将onclick
更改为模板中的ng-click
。