Angular 1.5 Component Two Way Binding Not Working
Asked Answered
A

1

9

I have an Angular 1.5.3 component that appears to not update the values for a two way binding. My controller changes the values which are passed to the component.

The component appears to read the default values when the controller is initialized but thereafter acts as if it is one way bound. Any future changes to the bound values are not read in the component.

I converted this from a similar functioning directive and the two way binding worked just fine. Is there an on change event, or something similar, I’m missing for components? Do I need to add specific logic to the component controller so the component template can read the bound values?

Menu template that implements the component:

<div data-ng-controller="MenuCtrl as ctrl">
    <!-- below shows ctrl values updating when controller changes them -->
    <pre>{{ctrl.menu}}</pre>
    <pre>{{ctrl.settings}}</pre>
    <!-- changes not reflected in component -->
    <my-sub-menu menu="ctrl.menu" settings="ctrl.settings"></my-sub-menu>
</div>

Sub menu component:

(function () {
'use strict';
angular
    .module('myApp.components')
    .component('mySubMenu', {
        bindings: {
            menu: '=',
            settings: '='
        },
        templateUrl: 'subMenu.component.html',
        controller: function () {
            // implementation that reads menu and settings
        }
    });
})();

Simplified sub menu component template:

<ul>
    <li ng-show="settings.menu1"><a href="/">Menu 1</a></li>
    <li ng-show="settings.menu2"><a href="/">Menu 2</a></li>
    <li ng-show="settings.menu3"><a href="/">Menu 3</a></li>
</ul>
<!-- changes to bound values not reflected in component template -->
<pre>{{menu}}</pre>
<pre>{{settings}}</pre>
Arrington answered 1/4, 2016 at 15:50 Comment(1)
Shouldn't it be {{$ctrl.menu}} and {{$ctrl.settings}}?Faught
F
9

As long as you don't have controller alias for your component, you could use default controllerAs alias as $ctrl. You could override it by having controllerAs option in component definition object.

Markup

<ul>
    <li ng-show="$ctrl.settings.menu1"><a href="/">Menu 1</a></li>
    <li ng-show="$ctrl.settings.menu2"><a href="/">Menu 2</a></li>
    <li ng-show="$ctrl.settings.menu3"><a href="/">Menu 3</a></li>
</ul>
<pre>{{$ctrl.menu}}</pre>
<pre>{{$ctrl.settings}}</pre>
Fordone answered 1/4, 2016 at 15:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.