Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Last active August 29, 2015 14:05
Show Gist options
  • Save ostretsov/cb8fef2ad13438a5ddab to your computer and use it in GitHub Desktop.
Save ostretsov/cb8fef2ad13438a5ddab to your computer and use it in GitHub Desktop.
AngularJS Collection controller for symfony2
sciApp.controller('AngularedCollectionController', ['$scope', '$compile', function ($scope, $compile) {
$scope.index = 1;
$scope.init = function (collectionId) {
var indexes = [];
$('#' + collectionId).find('input[type=hidden]').each(function () {
var attrName = $(this).attr('name');
var indexFinder = new RegExp('\\]\\[(\\d+)\\]\\[');
var finded = indexFinder.exec(attrName);
if (finded.length > 1) {
indexes.push(parseInt(finded[1]));
}
});
$scope.index = Math.max.apply(Math, indexes) + 1;
};
$scope.add = function (event) {
var $collectionItems = $(event.target).parent().find('div.collection-items');
var prototype = $collectionItems.attr('data-prototype');
var prototypeName = $collectionItems.attr('data-prototype-name');
var prototypeLabel = $collectionItems.attr('data-prototype-label');
// Just in case it doesn't get it
if (typeof prototypeName === 'undefined') {
prototypeName = '__name__';
}
if (typeof prototypeLabel === 'undefined') {
prototypeLabelss = '__name__label__';
}
var nameReplacePattern = new RegExp(prototypeName, 'g');
var labelReplacePattern = new RegExp(prototypeLabel, 'g');
prototype = prototype.replace(labelReplacePattern, $scope.index)
.replace(nameReplacePattern, $scope.index);
$newCollectionItem = $compile(prototype)($scope);
$collectionItems.append($newCollectionItem);
$scope.index++;
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment