Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5 component attribute presence

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');
    },

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.

like image 739
Seba Kerckhof Avatar asked May 25 '16 13:05

Seba Kerckhof


2 Answers

There is a built-in way to do this by injecting $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

like image 151
Ash Clarke Avatar answered Sep 27 '22 19:09

Ash Clarke


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'
});

Template:

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

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.

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

bindings: { sortable: '@' }

// within the controller:
var isSortable = vm.sortable !== undefined;
like image 35
simsibimsiwimsi Avatar answered Sep 27 '22 21:09

simsibimsiwimsi