Angular 1.5 组件属性存在 [英] Angular 1.5 component attribute presence
问题描述
我正在将一些 angular 指令重构为 angular 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');
},
我将如何使用 Angular 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 的值也将是一个字符串(如果属性未在组件标记上定义,则为 undefined).
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屋!