Lloyd Banks Lloyd Banks - 22 days ago 6
AngularJS Question

AngularJS 1.5 - How to Set Two Way Bindings on Component

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

I had to explicitly state the variable I wanted to bind:

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

Also, since controllerVariable is a string, I had to use the @ sign binding.