Angularjs 在指令中扩展控制器函数

Angularjs 在指令中扩展控制器函数,angularjs,Angularjs,我的控制器中有一个cancel函数,我想传递或绑定到指令。此函数基本上清除表单。像这样: app.controller('MyCtrl', ['$scope', function($scope){ var self = this; self.cancel = function(){... $scope.formName.$setPristine(); }; }]); app.directive('customDirective', function(

我的控制器中有一个
cancel
函数,我想传递或绑定到指令。此函数基本上清除表单。像这样:

app.controller('MyCtrl', ['$scope', function($scope){

    var self = this;

    self.cancel = function(){...
        $scope.formName.$setPristine();
    };
}]);

app.directive('customDirective', function() {

    return {
        restrict: 'E'
        scope: {
            cancel : '&onCancel'
        },
        templateUrl: 'form.html'
    };
});
form.html

<div>
    <form name="formName">

    </form>
</div>

但是,$setPristine()不起作用,因为控制器对表单DOM没有访问权。是否可以在指令中扩展控制器的
取消
功能,以便添加
$setPristine()

有人建议使用jQuery来选择表单DOM(如果这是唯一的方法的话),具体怎么做?是否有一种角度更高的方法来执行此操作?

由于
在指令内,控制器应该与之无关。知道它会破坏封装,即将实现细节从指令泄漏到控制器

一个可能的解决方案是向指令传递一个空的“holder”对象,并让指令用回调函数填充它。即:

app.controller('MyCtrl', ['$scope', function($scope) {
    var self = this;
    $scope.callbacks = {};

    self.cancel = function() {
        if( angular.isFunction($scope.callbacks.cancel) ) {
            $scope.callbacks.cancel();
        }
    };
});

app.directive('customDirective', function() {
    return {
        restrict: 'E'
        scope: {
            callbacks: '='
        },
        templateUrl: 'form.html',
        link: function(scope) {
            scope.callbacks.cancel = function() {
                scope.formName.$setPristine();
            };

            scope.$on('$destroy', function() {
                delete scope.callbacks.cancel;
            });
        }
    };
});
将其用作:

<custom-directive callbacks="callbacks"></custom-directive>


我也不确定我是否同意这一点,但是…

我应该在
范围
中使用
'='
而不是
'&
?我在某处读到表达式应该使用
&