Angular 1.5组件属性存在 [英] Angular 1.5 component attribute presence

查看:72
本文介绍了Angular 1.5组件属性存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm refactoring some angular directives to angular 1.5-style components.

我的某些指令的行为取决于存在的某个属性,因此该属性没有特定的布尔值.通过我的指令,我可以使用链接功能来完成此操作:

Some of my directives have behavior that depends on a certain attribute being present, so without the attribute having a specific boolean value. With my directives, I accomplish this using the link function:

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

我该如何使用有角度的1.5样式的组件语法做到这一点?

How would I do this with the angular 1.5-style component syntax?

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

One thing I could do is add a binding, but then I'd need to specify the boolean value. I'd like to keep my templates as-is.

推荐答案

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

Use bindings instead of the direct reference to the DOM attribute:

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>

使用单向绑定(由<"表示),在控制器实例(此处为视图模型的名称为vm)上的变量"sortable"的值,如果按如下所示设置,则为布尔值true.例子.如果您的sortable属性当前在模板中包含字符串,则'@'绑定也可能是合适的选择.在这种情况下,vm.sortable的值也将是一个字符串(如果未在组件标记上定义该属性,则为未定义).

Using a one-way-binding (indicated by the '<') the value of the variable 'sortable' on the controller instance (named vm for view model here) will be a boolean true if set as shown in the example. If your sortable attribute currently contains a string in your template an '@' binding may be a suitable choice as well. The value of vm.sortable would be a string (or undefined if the attribute is not defined on the component markup) in that case as well.

仅检查sortable属性的存在方式是这样的:

Checking for the mere presence of the sortable attribute works like this:

bindings: { sortable: '@' }

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

这篇关于Angular 1.5组件属性存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆