How to access a directive through a controller?

1

Does anyone know if it is possible to access a policy through a controller?

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

I do not have a specific code because I want to know how angular behaves about it, Controllers access to Directives.

    
asked by anonymous 09.12.2014 / 17:56

1 answer

2

Yes, you can do this through the $scope service:

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

Another controller:

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

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

In your HTML you can make the flag variable within the directive equal to 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 mount a Fiddle to show the code running, but I could not.

In this given example, the variables blabla and flag always have the same value. That is, every change made in one, will be reflected in the otura. This is a bi-directional bind. Unidirectional binds can be made. I suggest looking at the $scope service documentation for more details.

AngularJS Scopes

    
09.12.2014 / 20:03