我正在尝试通过指令传递一个在控制器中定义的方法到工厂。我似乎无法完全理解范围界定或最佳方法。
HTML:
<div ng-controller="testController as tc">
<h1>Testing from directive -> factory</h1>
<test-directive todo="doSomething()"> </test-directive>
<button ng-click="tc.executeSomething()">DO IT!</button>
</div>
JavaScript的:
var app = angular.module('testApp',[]);
app.controller('testController',[
'testFactory',
function(testFactory){
var self = this;
$scope.doSomething = function(){
alert('success!');
}
self.executeSomething = testFactory.delegate();
}]);
app.directive('testDirective',['testFactory'
function(testFactory){
return {
restrict: 'E',
scope: { todo = '&' },
link: function(scope, elem, attr){
if(attr.todo){
testFactory.delegate = scope.todo;
}
}
}
}]);
app.factory('testFactory',[
function(){
return {
delegate: function();
}
}]);