将方法从指令传递到工厂

时间:2015-10-26 19:48:53

标签: angularjs angularjs-scope angular-directive angular-services angular-controller

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

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

0 个答案:

没有答案