AngularJS 1.5 - How to Set Two Way Bindings on Component

Lloyd Banks picture Lloyd Banks · Nov 11, 2016 · Viewed 16.5k times · Source

Directives in Angular 1.X are set to have two way binding by default. Components have isolated scopes by default. I have a view that looks like:

<div class="my-view">
    {{controllerVariable}}
</div>

If I have the above set up as a directive, the controllerVariable loads correctly in the following situation:

<div ng-controller="myController">
    <my-view></my-view>
</div>

But if I have it set up as a component using the following:

myApp.component('myView', {
    templateUrl: '/path/to/view',
    bindings: '='
});

then the variable value isn't displayed. I have tried adding $ctrl to the variable:

<div class="my-view">
    {{$ctrl.controllerVariable}}
</div>

but this doesn't display the value either.

What am I missing here?

Answer

Gordnfreeman picture Gordnfreeman · Nov 11, 2016

You need to pass the value from the directive into the component:

<my-view passed-var='ctrl.passedVar'></my-view>

and in the component:

myApp.component('myView', {
    templateUrl: '/path/to/view',
    bindings: {
        passedVar: '='
    },
    controller: function () {
      var vm = this;
      console.log(vm.passedVar);
    }
});

then you will be able to access in the component as in the example

There are a few other ways to do it, such as using a service to handle the information or using require which would give your component access to the controller of the directive. You can find the above method and others here: https://docs.angularjs.org/guide/component.