In Angular 1.5, how to bind an attribute component as boolean?
Asked Answered
E

3

16

I would like to know if in Angular 1.5, when you use components, there is a simple way to bind an attribute which is a boolean without be converted as string with @.

For example, I have two components "app-menu" and "app-menuitem" without transclude. "app-menu" has only one attribute with is a list of items to create "app-menuitem".

<app-menu items="menuitems">

in the menuitems which is a json, you have an attribute by menuitem named "isactive" which a boolean value.

$scope.menuitems = [{ label : 'menuitem 1', isactive : true},{ label : 'menuitem 1', isactive : false}]

In the menuitem component :

angular.module('app')
    .component('appMenuitem', {
      transclude: false,
      controller: menuitemController,
      bindings: {
        label: '@',  
        isactive: '@' //<--- The problem is here because the boolean is converted as string
      },
      templateUrl: 'angular/components/simple/menuitem/menuitem.html'
    });

I don't know the best way to be sure at the end is a real boolean, not a string which makes me some bugs. Anyone has an idea ?

Edelsten answered 16/4, 2016 at 17:12 Comment(0)
A
27

In angular 1.5 onwards you can use < & @ for one way binding. The main differnece between these two is < has ability to pass an object with its original data type to component.

isactive: '<'
Air answered 16/4, 2016 at 17:16 Comment(0)
D
7

Just use a one-way binding instead of a string binding:

angular.module('app')
    .component('appMenuitem', {
      transclude: false,
      controller: menuitemController,
      bindings: {
        label: '@',  
        isactive: '<'
      },
      templateUrl: 'angular/components/simple/menuitem/menuitem.html'
    });
Dupont answered 16/4, 2016 at 17:16 Comment(0)
Y
4

< forces you to use true and false for your attribute values, which is not entirely HTML-like. For example, we often write:

<input type="text" disabled>

instead of

<input type="text" disabled="disabled">

To continue doing this with your AngularJS components, you can use a @ binding with parse-string-boolean (or similar) in $onChanges:

bindings: {
  paramSomething: '@something'
}

,

function $onChanges(changes) {
  if (changes.paramSomething) {
    switch (typeof this.paramSomething) {
      case 'string': {
        this.isSomething = parseBoolean(this.paramSomething, true);
        break;
      }
      case 'undefined': {
        this.isSomething = false;
        break;
      }
    }
  }

,

<my-component something></my-component>
Yah answered 15/3, 2018 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.