我想调用指令中定义的函数,与this stackoverflow question相反
我尝试过这个,但不起作用。
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);
},
}
});
这是一个工作 plunker .
更新
根据您的更新,事件通信不适合您的问题。
如何使用双向绑定(bind)将对象传递给指令并在该对象中定义 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';
};
},
}
});
已更新plunker .
关于javascript - Angular.js 在 Controller 中调用指令函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26805642/