Access parent property from directive controller with ControllerAs syntax and no $scope injection

1.1k views Asked by At

This is a followed up question from this.

How can I access a property defined in MyController from MyDirectiveController to change its value or just read it and use it for something else? (commented line in the code).

angular
    .module("app",[])
    .controller('MyController', MyController)
    .controller('MyDirectiveController', MyController)
    .directive('myDirective', myDirective);

function MyController() {
    var vm = this;
    vm.foo = 'fooController';
}

function myDirective() {
    return {
        restrict: 'E',
        scope: true,
        controller: MyDirectiveController,
        controllerAs: 'vm',
        template: '{{vmMy.foo}} - {{vm.foo}}'
    }
}

function MyDirectiveController() {
    var vm = this;
    vm.foo = 'fooDirective'; 

    // vmMyfoo = 'fooDirective';
}

Here is the jsfiddle.

1

There are 1 answers

7
dfsq On BEST ANSWER

You can use bindToController (available from v1.3.x) setting of directive to bind values to controller instance instead of scope object.

function myDirective() {
    return {
        restrict: 'E',
        scope: {
            value: '='
        },
        controller: MyDirectiveController,
        controllerAs: 'vm',
        bindToController: true,
        template: '{{vm.value}} - {{vm.foo}}'
    }
}

and in HTML you pass value to directive like this:

<div ng-controller="MyController as vmMy">
    <my-directive value="vmMy.foo"></my-directive>
</div>