Answer the question
In order to leave comments, you need to log in
Angular. How to add a scope to a directive and still have access to a variable from the controller's scope?
There is a controller and a directive.
The controller has a variable $scope.cntrlVar = 123;
If you define a directive with scope = false, then the directive can change the value of cntrVar. And if you specify for the scope directive, for example like this
scope:{
directiveVariable: '@'
}
Answer the question
In order to leave comments, you need to log in
Read about isolated scopes: https://docs.angularjs.org/guide/directive#isolati...
angular
.module('app')
.directive('myDirective', function () {
return {
scope: {
myVar: '=myDirective' // или через @, зависит от того что вам нужно
},
link: function (scope, el, attr) {
scope.$watch('myVar', function (ctrlVal) {
console.log(ctrlVal);
});
}
};
});
Take a closer look at
In case the directive is immediately inside the controller scope.$parent will point to the scope of the controller.
Although I don't think it's a good solution. If the directive will just refer to another scope, then perhaps you need to reconsider the architecture ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question