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?
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?
Share Improve this question asked May 10, 2013 at 13:23 LugaruLugaru 1,4603 gold badges25 silver badges39 bronze badges 3- 1 Why would you want to do that? – lucuma Commented May 10, 2013 at 13:38
- 2 you are not suppose to do it – Arun P Johny Commented May 10, 2013 at 13:56
- We moved to directive some part of code that similar for few views and this directive contains some variables that can be used in other parts of project. I wanna know is it posible to use this variables in a controller or not? – Lugaru Commented May 10, 2013 at 14:03
1 Answer
Reset to default 9The simplest way to acplish this is to make both your controller and directive get importantValue
and create()
from a service.
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.