How to access a directive through a controller?

Asked

Viewed 550 times

1

Can anyone tell if it is possible to access a directive through a controller?

The idea is for my controller to check a flag that is instantiated in the directive since it checks to show some results.

I don’t have a specific code because I want to know how the angular behaves about it, Controllers access to Directives.

1 answer

2


Yes, it is possible to do, through the service $scope:

Be your directive:

app.directive("foo", function () {
    "use strict";
    return {
        restrict: "E",
        template: "<div>{{ flag }}</div>",
        scope: {
            flag: "=flag"
        },
        controller: function ($scope) {
            $scope.flag = 1;
        }
    };
});

Some other kind of controller:

app.controller("Controller", [ function () {
    "use strict";
    this.blabla = 2;

    this.click = function () {
        this.blabla += 1;
    };
}]);

In your HTML you can make the variable flag within the directive has the same value as the controller variable blabla as follows:

<body ng-controller="Controller as ctrlr">
    <foo flag="ctrlr.blabla"></foo>
    <button ng-click="ctrlr.click()">Click!</button>
</body>

I tried to assemble a Fiddle to show the code running, but I couldn’t.

In this given example, the variables blabla and flag always have the same value. That is, any change made in one will be reflected in the otura. This is a bi-directional bind. It is possible to make unidirectional Binds. I suggest looking at the service documentation $scope for more details.

Angularjs Scopes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.