В ходе экспериментов с angular обнаружилась странная проблема с transclude. Такое ощущение что элемент который будет включен в директиву через трасклюд где-то кешируется.
В моем примере получается что элемент input
, который определенным образом включается в элемент span
, при использовании ng-repeat всегда один и тот же. В результате получается что он перемещается вниз по списку при каждом его включении.
код примера, и он же на plunker
// Code goes here
angular.module('app', [])
.controller('Ctrl', function($scope) {
$scope.items = [{
id: 1
}, {
id: 2
}, {
id: 3
}, ];
$scope.$on('remove', function(event, item) {
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
});
})
.directive('closable', function(){
return {
restrict: 'E',
require: 'ngModel',
transclude: true,
replace: true,
template: '<span> <a ng-click="close()">x</a></span>',
link: function(scope, elem, attrs, ngModel, transcludeFn){
scope.close = function(){
scope.$emit('remove', ngModel.$modelValue);
}
var transclusion = transcludeFn(scope);
console.log(transclusion, elem.find('span'));
elem.prepend(transclusion);
}
}
})
.directive('test', function() {
return {
restrict: 'E',
require: 'ngModel',
template: '<closable ng-model="item"><input type="text" ng-model="id"></closable>',
scope: {},
link: function(scope, elem, attrs, ngModel) {
ngModel.$formatters.push(function(modelValue) {
console.log('$formatters', modelValue);
return {
id: modelValue.id + 1
};
});
ngModel.$parsers.push(function(viewValue) {
ngModel.$modelValue.id = viewValue.id - 1;
console.log('$parsers', ngModel.$modelValue, viewValue);
return ngModel.$modelValue;
});
ngModel.$render = function() {
scope.id = ngModel.$viewValue.id;
scope.item = ngModel.$modelValue;
}
scope.$watch('id', function() {
ngModel.$setViewValue({
id: scope.id
});
});
}
};
})
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap@3.3.2" data-semver="3.3.2" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script data-require="angular.js@*" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="Ctrl">
<pre>{{ items|json }}</pre>
<ul class="list-unstyled">
<li ng-repeat="item in items">
<test ng-model="item"></test>
</li>
</ul>
</body>
</html>