AngularJS 1.5 - How to establish two-way component bindings

Directives in Angular 1.X default to two-way binding. By default, components have isolated areas. I have a view that looks like this:

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

If I have the above setting as a directive, it controllerVariableloads correctly in the following situation:

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

But if I configured it as a component using the following:

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

then the value of the variable is not displayed. I tried adding $ctrlto the variable:

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

but it also does not display the value.

What am I missing here?

+4
source share
2 answers

I had to explicitly specify the variable that I wanted to bind:

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

, controllerVariable , @.

+2

:

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

:

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

,

, , , . : https://docs.angularjs.org/guide/component.

+4

Source: https://habr.com/ru/post/1660545/


All Articles