我有一个与
Box file picker交互的指令.我的指令由两个单独的控制器使用,有可能在将来添加更多.
一旦用户选择文件/文件夹,Box文件选择器就可以设置回调函数,如下所示:
我的控制器正在使用该指令,并且将成功的回调逻辑作为范围变量,我正在传递给该指令.
调节器
- .controller('myController',function($scope) {
- $scope.onSuccessful = function(message) {
- alert('Success! Message: ' + message);
- };
- })
指示
- angular.module('myApp',[])
- .controller('myController',function($scope) {
- $scope.onSuccessful = function(message) {
- //message is undefined here
- alert('Success! Message: ' + message);
- };
- })
- .directive('myDirective',function() {
- return {
- restrict: 'A',scope: {
- success: '&'
- },link: function(scope,element) {
- //third party allows to subscribe to success and failure functions
- function ThirdPartySelect() {
- }
- ThirdPartySelect.prototype.success = function(callback) {
- this.callback = callback;
- };
- ThirdPartySelect.prototype.fireSuccess = function() {
- this.callback({
- foo: 'bar'
- });
- };
- var myThirdPartyInstance = new ThirdPartySelect();
- myThirdPartyInstance.success(function(message) {
- //message is still defined here,but not in the controller
- scope.success(message);
- });
- element.on('click',function() {
- myThirdPartyInstance.fireSuccess();
- });
- }
- };
- });
视图
- <div ng-controller="myController">
- <button my-directive success="onSuccessful(arg)">Test</button>
- </div>
我使用’=’而不是’&’来解决这个问题,但我想知道为什么它不能与’&’因为它应该用于method binding
解决方法
是的,要将控制器功能绑定到您的指令,您必须使用&绑定(表达式绑定),允许该指令调用由DOM属性定义的表达式或函数.
但是在您的指令中,当您调用绑定方法时,函数参数应该是一个对象,在定义函数时,该键与您在控制器中声明的参数相同.
所以在你的指令中,你必须更换:
- scope.success(message);
通过:
- scope.success({message:message.foo});
然后在您的HTML中,您必须更换:
- <button my-directive success="onSuccessful(arg)">Test</button>
通过:
- <button my-directive success="onSuccessful(message)">Test</button>
你可以看到Working Plunker