10

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

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

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

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

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

4

3 回答 3

10

使用绑定而不是直接引用 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”的值(此处为视图模型命名为 vm)如果按照示例中所示设置,则将是布尔值 true。如果您的可排序属性当前在您的模板中包含一个字符串,那么“@”绑定也可能是一个合适的选择。在这种情况下, vm.sortable 的值也将是一个字符串(如果该属性未在组件标记上定义,则为 undefined)。

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

bindings: { sortable: '@' }

// within the controller:
var isSortable = vm.sortable !== undefined;
于 2016-07-03T22:11:36.217 回答
3

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

angular
    .module('yourModule')
    .component('yourComponent', {
        templateUrl: 'your-component.component.html',
        controller: yourComponentsController
    });

function yourComponentController($element) {
    var sortable = $element[0].hasAttribute("sortable");
}
于 2016-12-02T15:29:56.950 回答
1

有一种内置方法可以通过注入$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

于 2019-06-10T15:02:37.550 回答