【问题标题】:Angular 1.5 component attribute presenceAngular 1.5 组件属性存在
【发布时间】:2016-09-23 03:11:29
【问题描述】:

我正在将一些角度指令重构为角度 1.5 样式的组件。

我的一些指令的行为取决于存在的某个属性,因此没有具有特定布尔值的属性。使用我的指令,我使用链接函数完成此操作:

link: function(scope,elem,attrs, controller){
      controller.sortable = attrs.hasOwnProperty('sortable');
    },

我将如何使用 Angular 1.5 样式的组件语法来做到这一点?

我可以做的一件事是添加一个绑定,但是我需要指定布尔值。我想保持我的模板不变。

【问题讨论】:

  • $attrs 注入您的控制器。

标签: angularjs angularjs-directive angularjs-components


【解决方案1】:

使用绑定而不是直接引用 DOM 属性:

angular.module('example').component('exampleComponent', {
  bindings: {
    sortable: '<'
  },
  controller: function() {
    var vm = this;
    var isSortable = vm.sortable;
  },
  templateUrl: 'your-template.html'
});

模板:

<example-component sortable="true"></example-component>

使用单向绑定(由“

检查 sortable 属性是否存在的工作方式如下:

bindings: { sortable: '@' }

// within the controller:
var isSortable = vm.sortable !== undefined;

【讨论】:

    【解决方案2】:

    如果您尝试检查是否存在没有值的属性,则使用绑定可能会起作用。如果您不关心该值,您可以通过在控制器上注入 $element 来检查它是否存在。

    angular
        .module('yourModule')
        .component('yourComponent', {
            templateUrl: 'your-component.component.html',
            controller: yourComponentsController
        });
    
    function yourComponentController($element) {
        var sortable = $element[0].hasAttribute("sortable");
    }
    

    【讨论】:

      【解决方案3】:

      有一种内置方法可以通过将$attrs 注入控制器来执行此操作。

      JS

      function MyComponentController($attrs) {
      
          this.$onInit = function $onInit() {
              this.sortable = !!$attrs.$attr.hasOwnProperty("sortable");
          }
      
      }
      
      angular
          .module("myApp", [])
          .component("myComponent", {
              controller: [
                  "$attrs",
                  MyComponentController
              ],
              template: "Sortable is {{ ::$ctrl.sortable }}"
          });
      

      HTML

      <my-component sortable>
      
      </my-component>
      
      <my-component>
      
      </my-component>
      

      示例

      JSFiddle

      【讨论】:

        猜你喜欢
        • 2017-01-22
        • 2016-08-31
        • 2016-10-19
        • 1970-01-01
        • 2016-12-20
        • 2016-09-10
        • 2017-04-15
        • 2016-08-08
        • 2017-01-16
        相关资源
        最近更新 更多