我有一个小角度应用程序,需要列出实体列表(在我的情况下是端点)。实体保存在数组中。出于这个例子的目的,让他们说他们在控制器上。
为了更好地分离逻辑,我创建了两个指令:endpointList
和端点,如下所示:
指令声明如下:
myApp.directive('endpointList', function () {
return {
restrict:'EA',
controller:'EndpointCtrl',
controllerAs:'epCtrl',
transclude: true,
replace: true,
templateUrl: 'endpoint-list.html'
};
})
.directive('endpoint', function ($compile, $log) {
return {
scope: {
scope:'=ngModel',
func:'&',
index:'@'
},
restrict:'EA',
replace:true,
templateUrl: 'endpoint.html',
require:'?^endpointList',
compile: function(tElem, tAtt) {
return function(scope, el, attr, ctrl) {
// ctrl.addResource(scope);
}
}
};
});
endpoint-list.html
...
<section>
<table class="table table-hover">
<thead>
<tr>
<th><input type="checkbox" ng-model="selectAll" ng-click="toggleSelectAll()"/></th>
<th>Label</th>
<th>Last updated</th>
<th>Status</th>
<th>Sync</th>
</tr>
</thead>
<tbody ng-transclude></tbody>
</table>
</section>
...
endpoint.html
的模板:
...
<td>
<a ng-click="sync()" class="glyphicon glyphicon-cloud">CALL ME</a>
</td>
...
我这样使用它们:
<endpoint-list>
<endpoint ng-repeat="ep in endpoints" scope="ep" ng-model="ep" func="selectEp(scope)" index="{{$index}}"></end-point>
</endpoint-list>
我的问题是在endpoint.html中我有一个链接,当点击时,我希望它在控制器上调用函数sync():
$scope.sync = function(endpoint) {
console.log('syncing:');
console.log(endpoint);
};
我该怎么做?任何提示都非常感谢。
答案 0 :(得分:1)
您可以创建一个中间人服务,将其注入您的控制器和指令,以及它。只要您的控制器引用了您的服务,您就可以直接从您的指令模板中调用该服务的方法。
myApp.service("middleManService", function() {
this.sync = function(endpoint) {
console.log('syncing:');
console.log(endpoint);
};
this.test = 'blah';
this.selectAll = false;
this.deleteBtnVisible = false;
this.editBtnVisible = false;
this.endpoints = [
{
label: '2.2.0',
url: 'https://version-2_2_0-api.company.com/test/test?api_key=xxx',
selected: false
},
{
label: '2.3.0',
url: 'https://version-2_3_0-api.company.com/test/test?api_key=xxx',
selected: false
}
];
};
});
将对此服务的引用添加到您的控制器:
myApp.controller('EndpointCtrl',
function ($scope, middleManService) {
$scope.middleManService = middleManService;
然后在你的html中,这样称呼它:
<td>
<a ng-click="middleManService.sync()" class="glyphicon glyphicon-cloud">CALL ME</a>
</td>