我想调用指令中定义的函数,与这个stackoverflow问题正好相反
我尝试了这个,但是没有用。
app.directive('myDirective', function() {
return {
link: function(scope, element, attrs) {
scope.someDirectiveFn = function(arg) {
return "in directive";
};
},
}
});
function MyCtrl($scope) {
alert($scope.someDirectiveFn());
}
那可能吗?我怎么能得到它?这是不好的做法吗?
编辑
我这样子:
.controller('MyCtrl', function($scope) {
alert($scope.func());
})
.directive('myDirective', function() {
return {
controller: function($scope, $element){
$scope.func = function() {
return "text";
};
}
}
});
您可以使用事件系统来实现。
首先,使用参数在您的范围内发出自定义事件。其次,使用angular $ on方法监听指令中的作用域。
app.controller('MyCtrl', function($scope) {
$scope.invokeDirectiveMethod = function() {
$scope.$emit('invokeMyDirectiveMethod', 'myParameter');
};
})
.directive('myDirective', function() {
return {
link: function(scope, element, attrs) {
var someDirectiveFn = function(event, arg) {
alert(arg + " in directive");
};
scope.$on('invokeMyDirectiveMethod', someDirectiveFn);
},
}
});
这是一个正在工作的朋克。
更新
根据您的更新,事件通信不适合您的问题。
如何使用两种方式将对象传递给指令并在该对象中定义someDirectiveFn呢?这样,您可以传递参数并从中返回值。
app.controller('MyCtrl', function($scope) {
$scope.shareObject = {};
$scope.invokeDirectiveMethod = function() {
if (angular.isFunction($scope.shareObject.someDirectiveFn)) {
$scope.message = $scope.shareObject.someDirectiveFn('from controller');
}
};
})
.directive('myDirective', function() {
return {
scope: {
'shareObject': '='
},
link: function(scope, element, attrs) {
scope.shareObject.someDirectiveFn = function(arg) {
return arg + ' from parameter';
};
},
}
});
更新了插件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句