Angular 1.5 component component attribute

I am refactoring some angular directives for angular components in the style of 1.5.

Some of my directives have behavior that depends on a specific attribute, therefore without an attribute that has a specific logical value. With my directives, I accomplish this using the link function:

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

How can I do this using angular 1.5-style component syntax?

One thing I could do is add a binding, but then I will need to specify a boolean value. I would like to keep my templates as is.

+8
source share
3 answers

Use bindings instead of directly referencing the DOM attribute:

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

Template:

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

Using a one-way binding (indicated by "<"), the value of the "sortable" variable in the controller instance (named vm for the view model here) will be the boolean true if it is set, as shown in the example. If your sortable attribute currently contains a string in your template, a “@” binding may be the appropriate choice. The vm.sortable value will be a string (or undefined if the attribute is not defined in the component markup) in this case.

Checking for a simple sort attribute works as follows:

 bindings: { sortable: '@' } // within the controller: var isSortable = vm.sortable !== undefined; 
+9
source

Using bindings may work, but not if you are trying to check for an attribute without a value. If you don't care about this value, you can simply check its existence by injecting $element on the controller.

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

There is a built-in way to do this by entering $attrs into the controller.

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> 

example

Jsfiddle

0
source

All Articles