James Allardice
James Allardice

Reputation: 165951

Can an AngularJS directive access a controller instance?

AngularJS has recently added support for a new "controller as" syntax which seems to be intended as a replacement for $scope:

var app = angular.module("example", []);
app.controller("ExCtrl", function () {
    this.property = "some value";
    /* Previously you would have to inject $scope and use
    $scope.property = "some value"; */
});

When you have a directive that occurs within a view that has a controller attached to it and you want to share data between the directive and the model, you could previously use $scope:

app.directive("exDirective", function () {
    return function (scope) {
        scope.property2 = "another value";
    };
});

Is there a way to use the "controller as" syntax and allow directives occurring within views using that controller to access its scope?

Upvotes: 1

Views: 2272

Answers (2)

Beyers
Beyers

Reputation: 9108

The "controller as" features publishes your controller into $scope with the name given. So in your example if you had ng-controller="ExCtrl as ctrl" then in your directive you should be able to access property2 using

scope.ctrl.property2 = "another value";

This is not really the recommended way to go about it though as it then tightly couples the directive with your controller. A better approach would be to either use isolated scope and pass in the property via an attribute or use a shared service to share data.

Upvotes: 2

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40296

The controller as syntax will place the controller in the scope with the given name. Any scope that prototypically inherits that scope, will also inherit the controller.

Fiddle example: http://jsfiddle.net/j5P77/

Directives with isolated scope could still use the controller with the (inelegant in my opinion) $parent scope.

Upvotes: 3

Related Questions