Ionic 1.3.1, based on Angular (1.5.x) brings the way to write components (something like directives, see: documentation).
This is a short write-up to show how we can define and use component instead of directive. Consider we need simple ionic toggle element with one letter inside (like the visual id of the toggle).
CSS:
Define classes for any used letters inside toggle; in this example assume we have 3 classes (.A, .B, .C to display ‘A’ or ‘B’ or ‘C’ letter).
.toggle .handle.A:before {
position: absolute;
top: -16.5px;
left: -25.5px;
padding: 18.5px 34px;
content: "A";
}
.toggle .handle.B:before {
position: absolute;
top: -16.5px;
left: -25.5px;
padding: 18.5px 34px;
content: "B";
}
.toggle .handle.C:before {
position: absolute;
top: -16.5px;
left: -25.5px;
padding: 18.5px 34px;
content: "C";
}
eg. .toggle .handle.A:before defines class .A and the part content: “A” the letter ‘A’
JS:
Define angular component the way close to directive.
.controller("appController", function(){
this.A = false;
this.B = false;
this.C = true;
})
.component("toggle", {
bindings: {
name: "@",
ngModel: "=",
toggleClass: "@class"
},
controller: function(){
},
template: '<label class="toggle" ng-class="$ctrl.toggleClass"><input type="checkbox" ng-model="$ctrl.ngModel"><div class="track"><div class="handle" ng-class="$ctrl.name"></div></div></label>'
})
appController has three initial variables (this.A, this.B, this.C) with initials values (false, false, true).
Our component’s name is ‘toggle’ and has three atributes: name, ngModel and toggleClass.
The attribute name is a string identifying the letter we want to display using the corresponding CSS class.
The attribute ngModel is tricky (not sure used right way…) and it is a glue between internal value (false/true) and ng-model variable’s value (two-way databinding).
The attribute toggleClass is a string that equals to attribute class of toggle element in HTML and it is used for color type of the toggle element (toggle-assertive, toggle-royal etc.).
HTML:
<ion-content class="padding" ng-controller="appController as vm">
<toggle class="toggle-royal" name="A" ng-model="vm.A"></toggle> value = {{vm.A}}
<br>
<toggle class="toggle-positive" name="C" ng-model="vm.C"></toggle> value = {{vm.C}}
<br>
<toggle class="toggle-calm" name="C" ng-model="vm.C"></toggle> value = {{vm.C}}
<br>
<toggle name="B" ng-model="vm.B"></toggle> value = {{vm.B}}
<br>
</ion-content>
**
The first element toggle has attribute class with toggle-royal value (the color of the toggle), attribute name equals to ‘A’ (so the letter ‘A’ will be displayed) and ng-model is set to variable vm.A.
Hope this help