【问题标题】:In Angular 1.5, how to bind an attribute component as boolean?在 Angular 1.5 中,如何将属性组件绑定为布尔值?
【发布时间】:2016-08-08 14:36:56
【问题描述】:

我想知道在 Angular 1.5 中,当你使用组件时,是否有一种简单的方法可以绑定一个布尔属性而不用 @ 转换为字符串。

例如,我有两个组件“app-menu”和“app-menuitem”没有嵌入。 “app-menu”只有一个属性,就是要创建“app-menuitem”的项目列表。

<app-menu items="menuitems">

在作为 json 的菜单项中,您有一个名为“isactive”的菜单项属性,它是一个布尔值。

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

在 menuitem 组件中:

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'
    });

我不知道最好的方法来确保最后是一个真正的布尔值,而不是一个让我产生一些错误的字符串。有人有想法吗?

【问题讨论】:

    标签: angularjs angularjs-directive binding components angularjs-components


    【解决方案1】:

    从 Angular 1.5 开始,您可以使用 &lt;@ 进行单向绑定。这两者之间的主要区别在于&lt; 能够将具有其原始数据类型的对象传递给组件。

    isactive: '<'
    

    【讨论】:

      【解决方案2】:

      只需使用单向绑定而不是字符串绑定:

      angular.module('app')
          .component('appMenuitem', {
            transclude: false,
            controller: menuitemController,
            bindings: {
              label: '@',  
              isactive: '<'
            },
            templateUrl: 'angular/components/simple/menuitem/menuitem.html'
          });
      

      【讨论】:

        【解决方案3】:

        &lt; 强制您使用 truefalse 作为属性值,这并不完全类似于 HTML。比如我们经常这样写:

        <input type="text" disabled>
        

        而不是

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

        要继续对您的 AngularJS 组件执行此操作,您可以在 $onChanges 中使用 @parse-string-boolean(或类似)的绑定:

        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>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-09-30
          • 2014-10-17
          • 1970-01-01
          • 2017-08-23
          • 2015-08-02
          • 2016-09-23
          • 2021-10-02
          相关资源
          最近更新 更多