Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5 Component Two Way Binding Not Working

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>
like image 335
Matt Riley Avatar asked Apr 01 '16 15:04

Matt Riley


1 Answers

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>
like image 146
Pankaj Parkar Avatar answered Sep 27 '22 21:09

Pankaj Parkar