[英]AngularJS communication between controller and directive
How to get some data from controller and use it inside directive thats not a problem. 如何从控制器获取一些数据并在指令中使用它没有问题。 But I stack with such situation when I need get data from directive and use it in my controller.
但是当我需要从指令中获取数据并在我的控制器中使用它时,我会堆叠这种情况。
For exmpl: 例如:
My controller: 我的控制器:
function MyController($scope, $location, myDirective) {
"use strict";
// here i need use scope.importantValue and create() method from directive
}
My 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...");
}
};
})
How I can use variables or/and methods from directive inside my controller? 如何在控制器中使用指令中的变量或/和方法?
The simplest way to accomplish this is to make both your controller and directive get importantValue
and create()
from a service. 实现此目的的最简单方法是使控制器和指令从服务中获取
importantValue
和create()
。
angular.module(/* Your module */).service('sharedData', function () {
return {
importantValue: "value",
create: function () {
console.log("Directive works...");
}
};
});
Now you can inject sharedData
into your directive and controller and access importantValue
and create()
from either place. 现在,您可以将
sharedData
注入指令和控制器,并从任一位置访问importantValue
和create()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.