如何从 Controller 获取一些数据并在指令中使用它不是问题。 但是当我需要从指令获取数据并在我的 Controller 中使用它时,我会遇到这种情况。
例如:
我的 Controller :
function MyController($scope, $location, myDirective) {
"use strict";
// here i need use scope.importantValue and create() method from directive
}
我的指令:
.directive("myDirective", function() {
"use strict";
return {
restrict: 'A',
template: '<div></div>',
replace: true,
scope: {
data: '=',
},
link: function(scope, elm) {
scope.importantValue = "value";
function create() {
console.log("Directive works...");
}
};
})
如何在我的 Controller 中使用指令中的变量或/和方法?
最佳答案
完成此操作的最简单方法是让您的 Controller 和指令都从服务中获取 importantValue
和 create()
。
angular.module(/* Your module */).service('sharedData', function () {
return {
importantValue: "value",
create: function () {
console.log("Directive works...");
}
};
});
现在您可以将 sharedData
注入(inject)到您的指令和 Controller 中,并从任一位置访问 importantValue
和 create()
。
关于javascript - Controller 和指令之间的 AngularJS 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16483336/