E
E
Egor2014-10-16 19:29:35
JavaScript
Egor, 2014-10-16 19:29:35

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: '@'
}

Then the directive can no longer access cntrVar.
How to make it possible to get access? It is not necessary to the whole controller, just one variable is enough.
PS do not offer a solution through events.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2014-10-16
@ByKraB

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);
                });
            }
        };
    });

N
Nikita Gushchin, 2014-10-16
@iNikNik

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 question

Ask a Question

731 491 924 answers to any question