Accessing parent property from directive controller with ControllerAs syntax and no scope nesting

This is the next question out of this .

How can I access the 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 a jsfiddle .

+3


source to share


1 answer


You can use bindToController

(available from v1.3.x) a directive parameter to bind values ​​to a controller instance instead of a scope object.

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

      



and in HTML, you are passing a value to a directive like:

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

      

+2


source







All Articles