Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 582
Lloyd Banks Avatar asked Nov 11 '16 20:11

Lloyd Banks


2 Answers

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.

like image 130
Gordnfreeman Avatar answered Sep 29 '22 10:09

Gordnfreeman


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.

like image 37
Lloyd Banks Avatar answered Sep 29 '22 10:09

Lloyd Banks