0

我正在尝试通过指令将控制器中定义的方法传递给工厂。我似乎无法完全理解范围界定或做到这一点的最佳方式。

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();
        }
}]);
4

0 回答 0