I have a very simple directive <my-card>
that lists out some data.
Example Usage
my-card(ng-repeat="item in parentCtrl.items" item='item')
The only main functionality I have is a button that toggles some additional data.
Here is my directive/controller definition. Should I use the link
function instead of creating a controller
? The reason I moved the logic into the MyCardCtrl
was so that I can easily unit test it.
MyCardCtrl
function MyCardCtrl() {
var vm = this;
this.cardClass = 'my-card-' + vm.item.type;
this.toggle = function() {
vm.item.showMore = !vm.item.showMore;
};
this.init = function(element) {
var img = angular.element(element[0].querySelector('.card-bg'));
img.css('background-image', 'url(' + vm.item.image_url + ')');
};
}
myCard Directive
function myCard() {
return {
restrict: 'E',
replace: true,
templateUrl: 'my-card.html'
scope: {
item: '='
},
link: function(scope, element, attrs, myCardCtrl) {
myCardCtrl.init(element);
},
controller: 'MyCardCtrl',
controllerAs: 'card',
bindToController: true
};
}
angular
.module('components')
.directive('myCard', [myCard])
.controller('MyCardCtrl', [MyCardCtrl]);
myCard template (written in Jade)
.my-card(ng-class='class.cardClass')
button(ng-click='card.toggleMeta()')
.my-card-content(ng-show='card.item.showMore')
// expose item object
h1 {{::item.name}}
.my-card-more(ng-show='!card.item.showMore')
.my-card-bg