|
import * as $ from "jquery"; |
|
import {find, extend, isArray} from "lodash"; |
|
import * as angular from "angular"; |
|
import * as mixitup from "mixitup"; |
|
|
|
class MixitupCtrl { |
|
mixer: any; |
|
items: any[]; |
|
trackBy: string; |
|
entryVarName: string; |
|
|
|
static defaultOptions = { |
|
trackBy: "id", |
|
entryVarName: "item" |
|
} |
|
|
|
static $inject = [ |
|
"$element", |
|
"$compile", |
|
"$scope" |
|
]; |
|
|
|
constructor( |
|
private $element, |
|
private $compile, |
|
private $scope |
|
) { |
|
/** |
|
* Prepare options |
|
* ----------------- |
|
*/ |
|
this.trackBy = this.trackBy ? this.trackBy : MixitupCtrl.defaultOptions.trackBy; |
|
this.entryVarName = this.entryVarName ? this.entryVarName : MixitupCtrl.defaultOptions.entryVarName; |
|
|
|
/** |
|
* Init item template |
|
* ----------------- |
|
*/ |
|
let template = find($($element).contents(), {nodeType: 8}).nodeValue; |
|
|
|
/** |
|
* Define 'render' function |
|
* ----------------- |
|
*/ |
|
let render = (item) => { |
|
let scope = this.$scope.$new() |
|
|
|
let scopeExtender = {} |
|
scopeExtender[this.entryVarName] = item; |
|
|
|
extend(scope, scopeExtender) |
|
let compiledTemplate = this.$compile(angular.element(template))(scope); |
|
return $(compiledTemplate).prop("outerHTML"); |
|
}; |
|
|
|
/** |
|
* init 'mixer' |
|
* ----------------- |
|
*/ |
|
this.mixer = mixitup(this.$element, { |
|
data: { |
|
uidKey: this.trackBy |
|
}, |
|
render: { |
|
target: render |
|
}, |
|
selectors: { |
|
target: ".card" |
|
} |
|
}); |
|
} |
|
|
|
$onChanges(changesObj) { |
|
if (changesObj.items) { |
|
this.renderList(); |
|
} |
|
} |
|
|
|
renderList() { |
|
if ( |
|
this.mixer && |
|
isArray(this.items) |
|
) { |
|
this.mixer.dataset(this.items); |
|
} |
|
} |
|
|
|
} |
|
|
|
let ngModule = angular.module("components.mixitup", []); |
|
|
|
ngModule.component("mixitup", { |
|
controller: MixitupCtrl, |
|
template: ($element) => { |
|
/** |
|
* Inside of the element is defined template of 'item' |
|
* since template can 'compilable' code (e.g. : component that changes its html after compilation) |
|
* we need ensure this code will not be compiled before use by 'mixitup' |
|
* so we 'comment' this element |
|
*/ |
|
let mixitupItem = $element.children()[0]; |
|
let mixitupItemCommented = document.createComment(mixitupItem.outerHTML); |
|
mixitupItem.replaceWith(mixitupItemCommented); |
|
}, |
|
bindings: { |
|
items: "<", |
|
trackBy: "@", |
|
entryVarName: "@" |
|
} |
|
}); |